public class Person
{
public delegate void Load();
public Load hander;
public string Name { get; set; }
public string Age { get; set; }
public void SetPerson()
{
hander = CreateLoad();
hander();
}
public void SetName()
{
Name = "某某某";
}
public Load CreateLoad()
{
DynamicMethod method = new DynamicMethod("SetName", null, null);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldloc_0);
ilGenerator.Emit(OpCodes.Ldstr, "某某某");
ilGenerator.Emit(OpCodes.Callvirt, this.GetType().GetProperty("Name").GetSetMethod());
ilGenerator.Emit(OpCodes.Ret);
return (Load)method.CreateDelegate(typeof(Load));
}
}
Person objP = new Person();
objP.SetPerson();
其实我就是想调用SetPerson方法,给Name属性赋值。但一直没有写正确。
请教高手这段emit代码该如何写?
this没有传递
有两个选择:
A、修改Load的签名,接受Person作为第一参数:
delegate void Load(Person p);
public Load CreateLoad()
{
DynamicMethod method = new DynamicMethod("SetName", typeof(void), new Type[]{typeof(Person)});
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldstr, "某某某");
ilGenerator.Emit(OpCodes.Callvirt, this.GetType().GetProperty("Name").GetSetMethod());
ilGenerator.Emit(OpCodes.Ret);
return (Load)method.CreateDelegate(typeof(Load));
}
B、不修改Load签名,但是在创建委托时,将某一个Person对象绑定到委托的第一参数上:
public Load CreateLoad(Person p)
{
DynamicMethod method = new DynamicMethod("SetName", typeof(void), new Type[]{typeof(Person)});
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldstr, "某某某");
ilGenerator.Emit(OpCodes.Callvirt, this.GetType().GetProperty("Name").GetSetMethod());
ilGenerator.Emit(OpCodes.Ret);
return (Load)method.CreateDelegate(typeof(Load), p);
}
原来写了ldloc_0是直接copy过来忘记改了,修改成ldarg_0