Do value types have Type objects?

2019-02-18 07:39发布

问题:

I am sure if the Title is explainatory or not, but I need some help understanding the concept.

We have class (reference types) that has method table associated with Type object. In addition to the method tables, the type object also contains all the static fields, type obj pointer and sync block index.

CLR refers to this method table when calling methods on instance of a reference type.

Method table contains the IL for a particular method that is used to change the state of instance fields.

Similarly we can define methods for a structs (value types).

At runtime, when a method is called on a value type, from where does the CLR refer to the IL of the method being called on the instance of the value type.

struct A
{
    // for Immutability of value type
    public readonly int a;

    public void MethodOnValueType()
    {
        // Some code here
    }
}

Where does CLR refer to find the IL for the method named "MethodOnValueType"?

Is there any Type Object for the value type in the managed heap?

I am sure for the case of reference types but confused for value types.

Thanks.

回答1:

Methods on value-types do not support polymorphism (except for the methods inherited from object, which are executed differently depending on whether they have been overridden): the call is a static call (not a virtual call). Basically, the "what method" part of the call information is resolved by the compiler and burned into the IL. It is then the job of the JIT to connect that call to the final method code.

There is no object-header etc on a value-type.

You can get a Type object for value-types, but that is not really related to method-call.



回答2:

Value types have Type objects, just as classes do.

Type intType1 = typeof(int);
Type intType2 = 100.GetType();

Debug.Assert(ReferenceEquals(intType1, intType2));

Dispatch to non-virtual methods is essentially the same for structs as it is for classes.

Virtual methods involve lookups in v-tables, which are a property of reference types. If you declare a struct that defines an interface, then call it via that interface, it will be boxed automatically into a reference type so that this virtual member may be invoked.

Hope that helps somewhat.



标签: c# .net clr