首页 / .NET / 正文

.NET[C#]中类型检测是用:typeof,GetType,还是is?

6558 发布于: 2018-01-02 读完约需2分钟

.NET[C#]中类型检测是用:typeof,GetType,还是is?

很多人的书写方式如下:

Type t = typeof(obj1);
if (t == typeof(int))
{
    //处理逻辑代码
}

你也可能写成这样的:

if (obj1.GetType() == typeof(int))
{
    //处理逻辑代码
}

或者是:

if (obj1 is int)
{
    //处理逻辑代码
}

那么到底该如何使用?typeof,GetType,is它们分别有什么区别吗?

首先,typeof,GetType,is 是三个分别不同的概念:

  • typeof 是用于获取类型 System.Type 对象的名称的;
  • GetType 是一个用于获取表达式的运行时类型的;
  • is 关键字将会返回实例是否在继承树中的判断值(布尔值:true 或者 false)

如下示例:

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);

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [后台系统模板]优质、整洁的基于Bootstrap 3& Bootstrap 4的响应式后台管理系统模板

下一篇: .NET[C#]泛型集合List<T>中如何按照泛型的某个属性排序,除了Linq你还能想什么哪些方式?

本文永久链接码友网 » .NET[C#]中类型检测是用:typeof,GetType,还是is?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册