好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
类型检查:使用 typeof, GetType 还是 is ? 关闭 返回上一级  

类型检查:使用 typeof, GetType 还是 is ?
+ 查看更多

发布日期:2018-03-07 14:09
分类:C#
浏览次数:164
我看到很多人用一下的方法:
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。
例如:
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" 
上一篇C#中使用反射来根据字符串获取属性值
.NET中,如何将一个字符串拆分成多行。下一篇
下一篇.NET中,如何将一个字符串拆分成多行。

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2022  苏州卡达网络科技有限公司 备案号:苏ICP备09008221号