谁能解释我为什么我们在拆箱过程中在大括号内写int [英] Can anybody explain me why do we write int in the braces during Unboxing

查看:71
本文介绍了谁能解释我为什么我们在拆箱过程中在大括号内写int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


拳击:
int a = 4;
对象Obj = a;

拆箱

int j =(int)obj;

谁能解释我为什么在大括号中编写int以及为什么我们不能编写convert.Toint32而不是编写(int)


感谢Advance

Hi All,


Boxing:
int a=4;
object Obj=a;

Unboxing

int j=(int)obj;

Can anybody explain me why do we write int in the braces and why can not we write convert.Toint32 instead of writing (int)


Thanx in Advance

推荐答案

可以.
使用演员表变得更短,更清晰.
You can.
It''s just shorter and clearer to use the cast.
object o = 123;
int i = (int) o;
int j = Convert.ToInt32(o);

这两个语句在功能上是等效的,但是前者更易于阅读,尤其是当表达式更复杂时而不是简单的对象.

The two statements are functionally equivalent, but the former is easier to read, particularly when the expression is more complicated than a simple object.


是的,当然.因为编译时类型System.Object.未知在分配时所引用对象的实际运行时类型是带框的System.Int32.因此,显式类型强制转换表明这是强制转换操作,可能成功也可能不成功.

当然,编译器无法跟踪代码并确定对象变量或先前赋值的初始化是对int对象,甚至是任何装箱的类型.在您的代码示例中,这并不是很明显,但是编写一些代码并证明在理论上静态地确定obj被引用对象的运行时类型是不可能的(在编译过程中),这非常容易. (一个想法:您可以使用伪随机数生成器将引用传递给某些方法,并将不同类型的对象分配给变量.)通过这种方式,编译器无法知道操作的实际运行时类型.

如果强制转换运算符尝试将对象引用强制转换为某种类型,该类型与所引用对象的运行时类型的分配不兼容,则此强制转换操作将引发强制转换异常.在这方面,演员是否涉及拆箱都没有关系.

—SA
Yes, of course. Because the compile-time type of obj is System.Object. It is not known that the actual run-time type of the referenced object at the moment of assignment is the boxed System.Int32. So, explicit type cast shows that this is the cast operation which may or may not be successful.

And of course, the compiler cannot trace the code and determine that the initialization of the object variable or the previous assignment was to the int object, or even any boxed type. From your code sample this is not so obvious, but it''s pretty easy to write some code and proof that it is theoretically impossible to determine the run-time type of the obj referenced object statically (during compilation). (One idea: you can pass the reference to some method using pseudo-random number generator and assigning objects of different types to the variable.) This way, the compiler cannot know actual run-time type of the operation.

If the cast operator tries to cast the object reference to some type which is not assignment compatible to the run-time type of the referenced object, this cast operation with throw a cast exception. In this respect, it does not matter if the cast involves unboxing or not.

—SA


这篇关于谁能解释我为什么我们在拆箱过程中在大括号内写int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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