类型检查:typeof、GetType还是is?
类型检查:typeof、GetType还是is?
我看到很多人使用以下代码:
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
个人觉得最后一种最清晰明了,但我是否有所遗漏?哪一种最好使用,还是个人喜好?
admin 更改状态以发布 2023年5月23日
在编译时获取类型时使用typeof
。在执行时获取类型时使用GetType
。很少有需要使用is
的情况,因为它执行强制转换,在大多数情况下,您最终仍然会进行强制转换。
还有第四种选项(尤其是如果您也要将对象转换为找到的类型时); 这就是使用as
。
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
获取实例的运行时类型。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 parameter) { return typeof(T).Name; } Animal probably_a_dog = new Dog(); Dog definitely_a_dog = new Dog(); Foo(probably_a_dog); // this calls Foo and returns "Animal" Foo (probably_a_dog); // this is exactly the same as above Foo (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 and returns "Dog" Foo (definitely_a_dog); // this is exactly the same as above. Foo (definitely_a_dog); // this calls Foo and returns "Animal". Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"