编程语言
首页 > 编程语言> > C#通过对象拆箱

C#通过对象拆箱

作者:互联网

我可以将字节转换为整数,没有任何问题.

byte a = 2;
int b = a;      // => unboxing, boxing or conversion?

当我先将字节转换为对象然后再转换为int时,我得到一个InvalidCastException.

byte a = 2;
object b = a;    // => boxing?
int c = (int) b; // => unboxing fails?

但是我可以通过使用Convert.ToInt32解决此问题.

byte a = 2;
object b = a;                // => boxing?
int c = Convert.ToInt32(b);  // => what happens here?

>为什么在第二个示例中出现InvalidCastException?
>后台的Convert.ToInt32是什么?
>我是否正确标记了装箱,拆箱和转换标签? /如果不确定示例中的正确术语是什么?
>转换运算符在这里吗?是否有关于基本类型的基本转换运算符的概述?

请不要犹豫,向我暗示其他我可能弄错或错过的事情.

解决方法:

Why do I get an InvalidCastException in the second example?

因为您指定要转换(同时取消装箱)(装箱的)变量的类型为其他类型.而且没有定义内置的,隐式的或显式的转换运算符,因此它会失败.

What does Convert.ToInt32 in the background?

This.它使用IConvertible接口进行转换.

Did I label boxing, unboxing and conversion correctly? / What is the correct term when in the examples where I’m not sure?

int b = a;      // => conversion
object b = a;    // => boxing
int c = (int) b; // => casting fails
int c = Convert.ToInt32(b);  // => what happens here: a method call that happens to do a conversion

Are the conversion operators at play here? Is there an overview about the basic conversion operators of the basic types?

是的,尽管在CLR中定义.

标签:unboxing,casting,boxing,c
来源: https://codeday.me/bug/20191025/1924762.html