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

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()。

其他回答

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

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

我更喜欢的是

也就是说,如果你使用的是is,你很可能没有正确使用继承。

假设那个人:实体,那个动物:实体。Feed是Entity中的一种虚拟方法(让Neil开心)

class Person
{
  // A Person should be able to Feed
  // another Entity, but they way he feeds
  // each is different
  public override void Feed( Entity e )
  {
    if( e is Person )
    {
      // feed me
    }
    else if( e is Animal )
    {
      // ruff
    }
  }
}

相当地

class Person
{
  public override void Feed( Person p )
  {
    // feed the person
  }
  public override void Feed( Animal a )
  {
    // feed the animal
  }
}

当您想在编译时获取类型时,请使用typeof。如果要在执行时获取类型,请使用GetType。很少有任何情况可以使用,因为它进行了强制转换,而且在大多数情况下,最终还是会强制转换变量。

还有第四个选项你还没有考虑(特别是如果你要将一个对象转换为你找到的类型);即用作。

Foo foo = obj as Foo;

if (foo != null)
    // your code here

这只使用一个强制转换,而此方法:

if (obj is Foo)
    Foo foo = (Foo)obj;

需要两个。

更新(2020年1月):

从C#7+开始,您现在可以内联转换,因此“is”方法现在也可以在一次转换中完成。

例子:

if(obj is Foo newLocalFoo)
{
    // For example, you can now reference 'newLocalFoo' in this local scope
    Console.WriteLine(newLocalFoo);
}

一切都不同。

typeof采用类型名(您在编译时指定)。GetType获取实例的运行时类型。如果实例在继承树中,则返回true。

实例

class Animal { } 
class Dog : Animal { }

void PrintTypes(Animal a) { 
    Console.WriteLine(a.GetType() == typeof(Animal)); // false 
    Console.WriteLine(a is Animal);                   // true 
    Console.WriteLine(a.GetType() == typeof(Dog));    // true
    Console.WriteLine(a is Dog);                      // true 
}

Dog spot = new Dog(); 
PrintTypes(spot);

T型怎么样?它是否也在编译时解决?

对T始终是表达式的类型。请记住,泛型方法基本上是一组具有适当类型的方法。例子:

string Foo<T>(T parameter) { return typeof(T).Name; }

Animal probably_a_dog = new Dog();
Dog    definitely_a_dog = new Dog();

Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.

Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal". 
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"