Amy*_*Amy 6 c# il reflection.emit
这是一项学习练习.我创建了一个方法,它接受一个Foo和一个字符串并设置A属性.我使用Reflector反汇编来生成以下发射代码.反汇编看起来像这样:
.method private hidebysig static void Spork(class ConsoleTesting.Foo f, string 'value') cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldarg.1
L_0002: callvirt instance void ConsoleTesting.Foo::set_A(string)
L_0007: ret
}
Run Code Online (Sandbox Code Playgroud)
好的,所以我在之后建模了我的发射代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace ConsoleTesting
{
class Foo
{
public string A { get; set; }
}
class Program
{
static Action<Foo, string> GenMethodAssignment(string propName)
{
MethodInfo setMethod = typeof(Foo).GetMethod("get_" + propName);
if (setMethod == null)
throw new InvalidOperationException("no property setter available");
Type[] argTypes = new Type[] { typeof(Foo), typeof(String) };
DynamicMethod method = new DynamicMethod("__dynamicMethod_Set_" + propName, null, argTypes, typeof(Program));
ILGenerator IL = method.GetILGenerator();
IL.Emit(OpCodes.Ldarg_0);
IL.Emit(OpCodes.Ldarg_1);
IL.Emit(OpCodes.Callvirt, setMethod);
IL.Emit(OpCodes.Ret);
method.DefineParameter(1, ParameterAttributes.In, "instance");
method.DefineParameter(2, ParameterAttributes.In, "value");
Action<Foo, string> retval = (Action<Foo, string>)method.CreateDelegate(typeof(Action<Foo, string>));
return retval;
}
static void Main(string[] args)
{
Foo f = new Foo();
var meth = GenMethodAssignment("A");
meth(f, "jason");
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个例外:
JIT Compiler encountered an internal limitation.
Run Code Online (Sandbox Code Playgroud)
krunk的意思是什么,我该如何解决?
编辑:
我想也许是因为目标方法是私有的,但我不太确定.从DynamicMethod MSDN页面:
以下代码示例创建一个与类型逻辑关联的DynamicMethod.此关联使其可以访问该类型的私有成员.
小智 2
好吧,我想通了。改变
IL.Emit(OpCodes.Callvirt, setMethod);
Run Code Online (Sandbox Code Playgroud)
到
IL.Emit(OpCodes.Call, setMethod);
Run Code Online (Sandbox Code Playgroud)
修复。我不知道为什么反汇编显示 CallVirt,但是呃。
| 归档时间: |
|
| 查看次数: |
4612 次 |
| 最近记录: |