我见过很多人使用以下代码:

Type t = obj1.GetType();
if (t == typeof(int))
    // Some code here

但我知道你也可以这样做:

if (obj1.GetType() == typeof(int))
    // Some code here

或者这个:

if (obj1 is int)
    // Some code here

就我个人而言,我觉得最后一个是最干净的,但我有什么遗漏吗?哪一个最好用,还是个人喜好?


当前回答

这取决于我在做什么。如果我需要bool值(例如,确定是否将强制转换为int),我将使用is。如果我确实出于某种原因需要该类型(例如,传递给其他方法),我会使用GetType()。

其他回答

我有一个要比较的Type属性,无法使用它(例如my_Type是_BaseTypetoLookFor),但我可以使用这些属性:

base_type.IsInstanceOfType(derived_object);
base_type.IsAssignableFrom(derived_type);
derived_type.IsSubClassOf(base_type);

请注意,在比较相同类型时,IsInstanceOfType和IsAssignableFrom返回true,其中IsSubClassOf将返回false。IsSubclassOf不适用于接口,而其他两个则适用

public class Animal {}
public interface ITrainable {}
public class Dog : Animal, ITrainable{}

Animal dog = new Dog();

typeof(Animal).IsInstanceOfType(dog);     // true
typeof(Dog).IsInstanceOfType(dog);        // true
typeof(ITrainable).IsInstanceOfType(dog); // true

typeof(Animal).IsAssignableFrom(dog.GetType());      // true
typeof(Dog).IsAssignableFrom(dog.GetType());         // true
typeof(ITrainable).IsAssignableFrom(dog.GetType()); // true

dog.GetType().IsSubclassOf(typeof(Animal));            // true
dog.GetType().IsSubclassOf(typeof(Dog));               // false
dog.GetType().IsSubclassOf(typeof(ITrainable)); // false

如果您使用的是C#7,那么是时候更新Andrew Hare的伟大答案了。模式匹配引入了一个很好的快捷方式,它在if语句的上下文中为我们提供了一个类型化变量,而不需要单独的声明/强制转换和检查:

if (obj1 is int integerValue)
{
    integerValue++;
}

对于像这样的单一演员来说,这看起来很乏味,但当你有很多可能的类型进入你的日常生活时,这真的很有魅力。以下是避免两次铸造的旧方法:

Button button = obj1 as Button;
if (button != null)
{
    // do stuff...
    return;
}
TextBox text = obj1 as TextBox;
if (text != null)
{
    // do stuff...
    return;
}
Label label = obj1 as Label;
if (label != null)
{
    // do stuff...
    return;
}
// ... and so on

尽可能缩小这段代码,以及避免同一对象的重复强制转换一直困扰着我

switch (obj1)
{
    case Button button:
        // do stuff...
        break;
    case TextBox text:
        // do stuff...
        break;
    case Label label:
        // do stuff...
        break;
    // and so on...
}

编辑:根据Palec的评论,更新了较长的新方法以使用开关。

这取决于我在做什么。如果我需要bool值(例如,确定是否将强制转换为int),我将使用is。如果我确实出于某种原因需要该类型(例如,传递给其他方法),我会使用GetType()。

性能测试类型of()与GetType():

using System;
namespace ConsoleApplication1
    {
    class Program
    {
        enum TestEnum { E1, E2, E3 }
        static void Main(string[] args)
        {
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test1(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test2(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            Console.ReadLine();
        }
        static Type Test1<T>(T value) => typeof(T);
        static Type Test2(object value) => value.GetType();
    }
}

调试模式下的结果:

00:00:08.4096636
00:00:10.8570657

释放模式下的结果:

00:00:02.3799048
00:00:07.1797128

我相信最后一个也涉及遗传(例如,狗是动物==真),这在大多数情况下更好。