发布日期:2018-03-26
类型检查:使用 typeof, GetType 还是 is ?+ 查看更多
类型检查:使用 typeof, GetType 还是 is ?
+ 查看更多
发布日期:2018-03-07 14:09
分类:C#
浏览次数:185
我看到很多人用一下的方法:
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
就个人而言,我觉得最后一种方法是最简洁的,但是有没有我遗漏的地方? 哪一种方法最好,还是根据个人喜好自由选择?
回答:
三者的不同点:typeof:需要一个类型名称(在编译时指定)。
GetType:获取实例的运行时类型。
is:如果实例在继承树中,则返回true。
GetType:获取实例的运行时类型。
is:如果实例在继承树中,则返回true。
例如:
class Animal { } class Dog : Animal { } void PrintTypes(Animal a) { print(a.GetType() == typeof(Animal)) // false print(a is Animal) // true print(a.GetType() == typeof(Dog)) // true } Dog spot = new Dog(); PrintTypes(spot);
那 typeof(T) 呢? 编译时也确实取值吗?
答案是肯定的。T 是表达式的类型。记住,泛型方法是一组使用类型参数声明的方法。 例如:
string Foo(T object) { 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"