私は次のクラスを持っています:
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