如何获取子类构造函数用于调用基类构造函数的硬编码参数?
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)
{
}
}
我想得到BaseMessage子类的所有硬编码格式字符串,即" Hello {0}"和"你好{0},我是{1}"
答案 0 :(得分:5)
在反射级别,唯一存在的位置是构造函数的方法体,它被编译为(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
}
或(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
中的值到达