How is ValueType.GetType() able to determine the type of the struct?

后端 未结 2 1607
清酒与你
清酒与你 2020-12-06 04:04

For a reference type, the object\'s memory layout is

| Type Object pointer|
|    Sync Block      |
|  Instance fields...|

For a value type,

2条回答
  •  情歌与酒
    2020-12-06 05:03

    Maybe Andrew H. took this as obvious and tried hard to make me understand +1. my light-bulb moment came from Jon Skeet.. again (this time via his book which I happened to be reading.. and around the exact region where the answers lay.

    • C# is a statically typed. Each variable has a type and it is known at compile time.
    • Value types can't be inherited. As a result, the VT objects don't need to carry around extra type information (as opposed to Ref Type objects, each of which have an object type header since the variable type and value/object type may differ.)

    Consider the snippet below. Although the variable type is BaseRefType, it points to an object of a more specialized type. For value types, since inheritance is outlawed, the variable type is the object's type.

    BaseRefType r = new DerivedRefType(); 
    ValueType v = new ValueType();
    

    My missing piece was bullet#1.
    . There seems to be some magic that lets the compiler/runtime know the 'type of the variable' given any arbitrary variable. So the runtime somehow knows that ob is of MyStruct type, even though the VT object itself has no type information.

    MyStruct ob = new MyStruct();
    ob.WhoAmI();                          // no box ; defined in MyStruct
    Console.WriteLine(ob.GetHashCode());  // no box ; overridden in ValueType
    Console.WriteLine( ob.GetType() );    // box ; implemented in Object
    

    Due to this, I am able to invoke methods defined in MyStruct (and ValueType for some reason) without boxing to a RefType.

提交回复
热议问题