装箱和拆箱的int和string [英] boxing and unboxing in int and string
问题描述
我有点困惑的装箱和拆箱。根据定义
I am little bit confused in boxing and unboxing. According to its definition
拳击是值类型为引用类型(对象)的隐式转换。
拆箱是引用类型(对象)的显式转换为其等效值类型。
Boxing is implicit conversion of ValueTypes to Reference Types (Object).
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes.
来描述这个最好的例子就是
the best example for describing this is
int i = 123; object o = i; // boxing
和
o = 123; i = (int)o; // unboxing
但我的问题是,INT是否是值类型,字符串是引用类型,所以
But my question is that whether int is value type and string is reference type so
int i = 123; string s = i.ToString();
和
s = "123"; i = (int)s;
这是拳击和拆箱或不???
Is this an example of boxing and unboxing or not???
推荐答案
调用的ToString
是不是拳击。它创建恰好包含您的INT的文本再presentation一个新的字符串。
Calling ToString
is not boxing. It creates a new string that just happens to contain the textual representation of your int.
在调用(对象)1
对包含一个int堆这将创建一个新的实例。但它仍然是一个 INT
。 (您可以验证与 o.GetType()
)
When calling (object)1
this creates a new instance on the heap that contains an int. But it's still an int
. (You can verify that with o.GetType()
)
串不能以铸转换为 INT
。所以,你的code将无法编译。
String can't be converted with a cast to int
. So your code will not compile.
如果你先投你的字符串对象
您code编译但在运行时失败,因为你的对象是没有装箱的int。您只能拆箱的值类型到完全正确的类型(或相关联的可为空)。
If you first cast your string to object
your code will compile but fail at runtime, since your object is no boxed int. You can only unbox an value type into the exactly correct type(or the associated nullable).
两个例子:
破碎:
object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int
工作
object o=i;// o is a boxed int
int i2=(int)o;//works
这篇关于装箱和拆箱的int和string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!