我见过很多人使用以下代码:
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)
就个人而言,我觉得最后一个是最干净的,但有什么我想念的吗?哪一个最好用,还是个人喜好?
这两者之间的确切区别是什么?
// 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)