什么是更好的方式来检查一个给定的对象是一个特定的值类型? [英] What is a better way to check that a given object is a particular value type?
问题描述
下面是2常用的手法拆箱前检查。
myObject.GetType()== typeof运算(MyValueType)
IL_0001:callvirt System.Object.GetType
IL_0006:ldtoken UserQuery.MyValueType
IL_000B:拨打System.Type.GetTypeFromHandle
IL_0010:拨打System.Type.op_Equality
myObject的是MyValueType
IL_0001:isinst UserQuery.MyValueType
另外,我很奇怪,为什么C#调用 System.Type.op_Equality
而不是 CEQ
这不就是引用相等检查?
更新
其实,有一个3路。 (从C#果壳中的5.0)
MyValueType? X = myObject的作为MyValueType ?;
然后检查 x.HasValue
,并使用 x.Value
3的人会使用哪?
我想知道为什么C#调用
System.Type.op_Equality
而不是CEQ
。
块引用>
由于类型比较了价值,而不是引用。有可能是内存中的两个类型的对象指的是同一类型。
这三个中的一个,你会用哪个?
块引用>
如果你想知道一个实例是一种特殊类型的,有运营商专为解决这一问题,单靠问题:
是
。为什么你会永远的不的使用是专门为您解决问题的工具?如果您要更换屋顶和你有一个屋顶斧头和锤子之间进行选择,我希望你可以使用屋顶前嫌。
现在,如果你需要既做了型式试验的并获得价值的话,我会倾向于使用
为
,因为这是运营商的专为解决问题Below are the 2 commonly used approaches to check before unbox.
myObject.GetType() == typeof(MyValueType) IL_0001: callvirt System.Object.GetType IL_0006: ldtoken UserQuery.MyValueType IL_000B: call System.Type.GetTypeFromHandle IL_0010: call System.Type.op_Equality myObject is MyValueType IL_0001: isinst UserQuery.MyValueType
Plus, I am wondering why C# calls
System.Type.op_Equality
instead ofceq
Isn't that reference equality check?Update
Actually, there is a 3rd way. (from C# 5.0 in a Nutshell)
MyValueType? x = myObject as MyValueType?;
Then check
x.HasValue
and usex.Value
Which one of the 3 would you use?
解决方案I am wondering why C# calls
System.Type.op_Equality
instead ofceq
.Because types are compared by value, not by reference. There could be two type objects in memory that refer to the same type.
Which one of the three would you use?
If you want to know whether an instance is of a particular type, there is an operator specifically designed to solve that problem and that problem alone:
is
. Why would you ever not use the tool that was specifically designed to solve your problem? If you're replacing a roof and you have a choice between a roofing hatchet and a hammer, I hope you would use the roofing hatchet.Now, if you need to both do a type test and obtain the value then I would be inclined to use
as
because that is the operator specifically designed to solve that problem.这篇关于什么是更好的方式来检查一个给定的对象是一个特定的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!