【发布时间】:2012-07-12 09:38:45
【问题描述】:
我有以下课程:
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 操作码和 this 对象),但是当我尝试访问静态字段时,我收到异常:
System.InvalidProgramException was unhandled
Message=InvalidProgramException
【问题讨论】:
标签: c# windows-phone-7 reflection static dynamicmethod