How to get the base constructor calling parameters with Reflection

How to get the hard code used by the constructor of a subclass to call the constructor of the base class?

public class BaseMessage
{
    public BaseMessage(string format, params string[] parameteres)
    {
    }
}

public class HelloMessage : BaseMessage
{
    public HelloMessage(string name) : base("Hello {0}", name)
    {
    }
}

public class IntroductionMessage : BaseMessage
{
    public IntroductionMessage(string name, string myName) : base("Hello {0}, I am {1}", name, myName)
    {
    }
}

I would like to get the entire string formatting string for subclasses of BaseMessage, that is, "Hello {0}" and "Hello {0}, I {1}"

+4
source share
1 answer

At the reflection level, the only place that it exists is in the body of the constructor method, which compiles as ( HelloMessage):

.method public hidebysig specialname rtspecialname instance void
    .ctor(string name) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldstr "Hello {0}"
    L_0006: ldc.i4.1 
    L_0007: newarr string
    L_000c: dup 
    L_000d: ldc.i4.0 
    L_000e: ldarg.1 
    L_000f: stelem.ref 
    L_0010: call instance void BaseMessage::.ctor(string, string[])
    L_0015: ret 
}

or ( IntroductionMessage):

.method public hidebysig specialname rtspecialname instance void
    .ctor(string name, string myName) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldstr "Hello {0}, I am {1}"
    L_0006: ldc.i4.2 
    L_0007: newarr string
    L_000c: dup 
    L_000d: ldc.i4.0 
    L_000e: ldarg.1 
    L_000f: stelem.ref 
    L_0010: dup 
    L_0011: ldc.i4.1 
    L_0012: ldarg.2 
    L_0013: stelem.ref 
    L_0014: call instance void BaseMessage::.ctor(string, string[])
    L_0019: ret 
}

, (MethodInfo.GetMethodBody().GetILAsByteArray()) (, IL, , ). , , , , . IL, ... : .

:

  • , format BaseMessage
  • , , Roslyn -
  • -, ; .
+5

Source: https://habr.com/ru/post/1692301/


All Articles