我有以下课程:
public class TestClass
{
public static readonly string HELLO = "Hello, ";
public static string SayHello(string name)
{
return HELLO + name;
}
}
我想通过 DynamicMethod 访问 HELLO 的静态字段。GetValue 的标准反射有效:
public static string GetViaInvoke()
{
Type tcType = typeof(TestClass);
FieldInfo fi = tcType.GetField("HELLO");
string result = fi.GetValue(null) as string;
return result;
}
但我需要类似的东西(OpCodes 来自类似方法的 ILDasm):
public static string GetViaDynamicMethod()
{
Type tcType = typeof(TestClass);
FieldInfo fi = tcType.GetField("HELLO");
DynamicMethod dm = new DynamicMethod("getHello", typeof(string), Type.EmptyTypes);
ILGenerator iL = dm.GetILGenerator();
iL.DeclareLocal(typeof(string));
iL.Emit(OpCodes.Nop);
iL.Emit(OpCodes.Ldsfld, fi);
iL.Emit(OpCodes.Stloc_0);
iL.Emit(OpCodes.Br_S, 0x09);
iL.Emit(OpCodes.Ldloc_0);
iL.Emit(OpCodes.Ret);
Func<string> fun = dm.CreateDelegate(typeof(Func<string>)) as Func<string>;
string result = fun();
return result;
}
这个想法非常简单,动态方法适用于非静态字段(ldfld 操作码和此对象),但是当我尝试访问静态字段时,我收到异常:
System.InvalidProgramException was unhandled
Message=InvalidProgramException