相关疑难解决方法(0)

类型检查:typeof,GetType还是?

我见过很多人使用以下代码:

Type t = typeof(obj1);
if (t == typeof(int))
    // Some code here
Run Code Online (Sandbox Code Playgroud)

但我知道你也可以这样做:

if (obj1.GetType() == typeof(int))
    // Some code here
Run Code Online (Sandbox Code Playgroud)

或这个:

if (obj1 is int)
    // Some code here
Run Code Online (Sandbox Code Playgroud)

就个人而言,我觉得最后一个是最干净的,但有什么我想念的吗?哪一个最好用,还是个人喜好?

c#

1435
推荐指数
8
解决办法
93万
查看次数

typeof和is关键字有什么区别?

这两者之间的确切区别是什么?

// When calling this method with GetByType<MyClass>()

public bool GetByType<T>() {
    // this returns true:
    return typeof(T).Equals(typeof(MyClass));

    // this returns false:
    return typeof(T) is MyClass;
}
Run Code Online (Sandbox Code Playgroud)

c# generics types

42
推荐指数
6
解决办法
4051
查看次数

标签 统计

c# ×2

generics ×1

types ×1