问题
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 of ceq
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 use x.Value
Which one of the 3 would you use?
回答1:
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.
回答2:
If an overloaded ==
operator exists it is being preferred. If not, what would be the point of it?
Besides of doing the measurement to find out what is faster, I think the type equality check will be faster because the JIT contains a special optimization that recognizes this pattern and optimizes it to the fullest. On the other hand, maybe the isinst
will be compiled to the same instructions if the JIT recognizes that you are casting to a value type (which cannot possibly have subtypes).
Your 3rd method of checking cannot beat the 2nd because you are requiring the JIT to do more than before. At best this optimized back into the 2nd form, but I would be surprised to see that given the poor optimization capabilities of the current JIT.
来源:https://stackoverflow.com/questions/17634395/what-is-a-better-way-to-check-that-a-given-object-is-a-particular-value-type