Calling ToString
is not boxing. It creates a new string that just happens to contain the textual representation of your int.
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()
)
String can't be converted with a cast to int
. So your code will not compile.
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).
Two examples:
Broken:
object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int
Working:
object o=i;// o is a boxed int
int i2=(int)o;//works
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…