什么是更好的方式来检查一个给定的对象是一个特定的值类型? [英] What is a better way to check that a given object is a particular value type?

查看:150
本文介绍了什么是更好的方式来检查一个给定的对象是一个特定的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是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 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?

解决方案

I am wondering why C# calls System.Type.op_Equality instead of ceq.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆