小编典典

类型检查:typeof、GetType 或 is?

c#

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

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

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

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

或这个:

if (obj1 is int)
    // Some code here

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


阅读 513

收藏
2022-02-17

共1个答案

小编典典

都是不同的。

  • typeof采用类型名称(您在编译时指定)。
  • GetType获取实例的运行时类型。
  • is如果实例在继承树中,则返回 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);

怎么样typeof(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"
2022-02-17