C# 通过对象拆箱

c# unboxing via object

我可以毫无问题地将 byte 转换为 int

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

当我先将 byte 转换为 object 然后再转换为 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?

请不要犹豫,提示我其他我可能弄错或遗漏的事情。

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 中定义。

Why do I get an InvalidCastException in the second example?

您只能在原始类型中拆箱

What does Convert.ToInt32 in the background?

它包含一个转换

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

byte a = 2;
int b = a;      // convertation (byte to int)

object b = a;    // boxing
int c = (int) b; //unboxing

object b = a;                // boxing
int c = Convert.ToInt32(b);  // convertation (object to int)

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

您可以反映框架代码以更深入地了解它的工作原理。

应该是

object b = a;    // => boxing
int c = (int) b;  //Un-boxing