我见过很多人使用以下代码:
Type t = obj1.GetType();
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
还有第四个选项是你没有考虑的(特别是如果你也要将对象强制转换为你找到的类型);那就是使用 .as
Foo foo = obj as Foo;
if (foo != null)
// your code here
这仅使用一种强制转换,而此方法:
if (obj is Foo)
Foo foo = (Foo)obj;
需要两个。
更新(2020年<>月):
例:
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}
网友回答:
都是不同的。
typeof
采用类型名称(在编译时指定)。GetType
获取实例的运行时类型。is
如果实例位于继承树中,则返回 true。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);
怎么样?是否也在编译时解决?
typeof(T)
是的。T 始终是表达式的类型。请记住,泛型方法基本上是具有适当类型的一大堆方法。例:
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"
网友回答:
1.
Type t = typeof(obj1);
if (t == typeof(int))
这是非法的,因为仅适用于类型,不适用于变量。我假设 obj1 是一个变量。因此,这种方式是静态的,并且在编译时而不是运行时完成其工作。typeof
typeof
2.
if (obj1.GetType() == typeof(int))
这是如果完全是类型。如果派生自 ,则 if 条件将为 。true
obj1
int
obj1
int
false
3.
if (obj1 is int)
这是 if 是一个 ,或者如果它派生自一个名为 的类,或者如果它实现了一个名为 的接口。true
obj1
int
int
int
模板简介:该模板名称为【类型检查:typeof、GetType,还是?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。