类型检查:typeof、GetType 或 is? [英] Type Checking: typeof, GetType, or is?
本文介绍了类型检查:typeof、GetType 或 is?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过很多人使用以下代码:
Type t = typeof(obj1);如果 (t == typeof(int))//这里有一些代码
但我知道你也可以这样做:
if (obj1.GetType() == typeof(int))//这里有一些代码
或者这个:
if (obj1 is int)//这里有一些代码
就我个人而言,我觉得最后一个是最干净的,但是有什么我遗漏的地方吗?哪个最好用,还是个人喜好?
解决方案
都不同.
typeof
采用类型名称(您在编译时指定).GetType
获取实例的运行时类型. 如果实例在继承树中,is
返回 true.
示例
class Animal { }狗类:动物{}void PrintTypes(Animal a) {Console.WriteLine(a.GetType() == typeof(Animal));//错误的Console.WriteLine(a 是动物);//真的Console.WriteLine(a.GetType() == typeof(Dog));//真的Console.WriteLine(a 是狗);//真的}狗点 = new Dog();PrintTypes(现货);
<小时><块引用>
typeof(T)
怎么样?编译时也解决了吗?
是的.T 始终是表达式的类型.请记住,泛型方法基本上是具有适当类型的一大堆方法.示例:
string Foo(T 参数) { return typeof(T).Name;}动物可能_a_dog = new Dog();绝对狗_a_dog = new Dog();Foo(可能是_a_dog);//这会调用 Foo并返回动物"Foo<Animal>(probably_a_dog);//这和上面的完全一样Foo<Dog>(可能是_a_dog);//!!!这不会编译.该参数需要一个 Dog,您不能传入一个 Animal.Foo(绝对_a_dog);//这会调用 Foo并返回狗"Foo<Dog>(绝对_a_dog);//这和上面的完全一样.Foo<Animal>(绝对_a_dog);//这会调用 Foo并返回动物".Foo((动物)绝对_a_狗);//和上面一样,返回Animal"
I've seen many people use the following code:
Type t = typeof(obj1);
if (t == typeof(int))
// Some code here
But I know you could also do this:
if (obj1.GetType() == typeof(int))
// Some code here
Or this:
if (obj1 is int)
// Some code here
Personally, I feel the last one is the cleanest, but is there something I'm missing? Which one is the best to use, or is it personal preference?
解决方案
All are different.
typeof
takes a type name (which you specify at compile time).GetType
gets the runtime type of an instance.is
returns true if an instance is in the inheritance tree.
Example
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);
What about
typeof(T)
? Is it also resolved at compile time?
Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:
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"
这篇关于类型检查:typeof、GetType 或 is?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文