How does the CLR know the type of a boxed object?

风流意气都作罢 提交于 2019-12-10 01:48:11

问题


When a value type is boxed, it is placed inside an untyped reference object. So what causes the invalid cast exception here?

long l = 1;
object obj = (object)l;
double d = (double)obj;

回答1:


No, it's not placed in an untyped object. For each value type, there's a boxed reference type in the CLR. So you'd have something like:

public class BoxedInt32 // Not the actual name
{
    private readonly int value;
    public BoxedInt32(int value)
    {
        this.value = value;
    }
}

That boxed type isn't directly accessible in C#, although it is in C++/CLI. Obviously that knows the original type. So in C# you have to have a compile-time type of object for the variable but that doesn't mean that's the actual type of the object.

See the ECMA CLI spec or CLR via C# for more details.




回答2:


I answer your question here:

http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx




回答3:


Jon Skeet's answer covers the why; as for the how to get around it, here's what you have to do:

long l = 1;
object obj = (object)l;
double d = (double)(long)obj;

The reason for the dual cast is this; when .NET unboxes the variable, it only knows how to unbox it into the type it was boxed from (long in your example.) Once you've unboxed it and you have a proper long primitive, you can then cast it to double or any other type castable from long.



来源:https://stackoverflow.com/questions/2651754/how-does-the-clr-know-the-type-of-a-boxed-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!