有一类:
public class Test
{
private string[] _array;
public Test(int n)
{
_array = new string[n];
}
//return _array[i];
public string Method(int i)
{
var ownerType = this.GetType();
DynamicMethod method = new DynamicMethod("test_method",
typeof(string),
new Type[] { typeof(int) },
ownerType );
var generator = method.GetILGenerator();
var arrayField = ownerType.GetField("_array", BindingFlags.NonPublic | BindingFlags.Instance);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, arrayField);
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldelem_Ref);
generator.Emit(OpCodes.Ret);
return (string)method.Invoke(null, new object[] { i });
}
}
调用时Method
会抛出异常
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation. Inner Exception: NullReferenceException: Object reference not set to an instance of an object.'
。如何加载当前类实例以便其成员在 DynamicMethod 中可用?
this
作为第一个参数隐式传递。所以新方法实际上有2个参数
而且,打电话的时候,你也必须同时通过