How is Reflection implemented in C#?

前端 未结 4 730
我寻月下人不归
我寻月下人不归 2020-12-09 09:54

I got curious as to where Type.GetType() is implemented, so I took a peek at the assembly and noticed Type.GetType() calls base.GetType()

4条回答
  •  时光取名叫无心
    2020-12-09 10:31

    It might not answer you question directly. However, here is a little outline of how managed code knows everything about types.

    1. Whenever you compile code the compiler analyzes/parses the source files and collects information it encounters. For example take a look at class below.

      class A
      {
        public int Prop1 {get; private set;}
        protected bool Met2(float input) {return true;}
      }
      

      The compiler can see that this is an internal class with two members. Member one is a property of type int with private setter. Member 2 is a protected method with name Met2 and type boolean that takes float input (input name is 'input'). So, it has all this information.

    2. It stores this information in the assembly. There are a couple of tables. For example classes (types) all leave in one table, methods live in another table. Think in turms of SQL tables, though they are definitely are not.

    3. When a user (developer) wants to know information about a type it calls GetType method. This method relies on objects hidden field - type object pointer. This object is basically a pointer to a class table. Each class table will have a pointer to the first method in methods table. Each method record will have a pointer to the first parameter in the parameters table.

    PS: this mechamism is key to making .NET assemblies more secure. You cannot replace pointers to methods. It will break the signature of the assebmly.

    JIT compilation relies heavily on this tables as well

提交回复
热议问题