我想创建一个动态方法,它接受Int32
参数并返回它的字符串表示:
public class Item
{
public int Age { get; } = 22;
}
static void CreateDynamicMethod()
{
var ageGet = typeof(Item).GetProperty("Age").GetGetMethod(true);
var intToString = typeof(int).GetMethod("ToString", new Type[] { });
var dm = new DynamicMethod("getAgeString", typeof(string), new[] { typeof(Item) }, typeof(Item).Module);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); //load Item instance on stack
il.Emit(OpCodes.Callvirt, ageGet); //age 44 on stack
il.Emit(OpCodes.Call, intToString); //call tostring for age, "44" on stack now
il.Emit(OpCodes.Ret); //return "44"
var agestr = (Func<Item, string>)dm.CreateDelegate(typeof(Func<Item, string>));
Console.WriteLine(agestr.Invoke(new Item()));
}
但该方法因异常而失败Object reference not set to an instance of an object
。我错过了什么?
更新:我检查了我的方法的 C# 版本的 MSIL:
static string GetAge(Item item)
{
return item.Age.ToString();
}
我发现我需要在调用之前从堆栈中弹出整数intToString
。完整版本:
var dm = new DynamicMethod("getAgeString", typeof(string), new[] { typeof(Item) }, typeof(Item).Module);
var il = dm.GetILGenerator();
il.DeclareLocal(typeof(int)); //[NEW] declare local integer variable
il.Emit(OpCodes.Ldarg_0); //load Item instance on stack
il.Emit(OpCodes.Callvirt, ageGet); //age 44 on stack now
il.Emit(OpCodes.Stloc_0); //[NEW] pop ineteger from stack to local variable
il.Emit(OpCodes.Ldloca_S, 0); //[NEW] load address of integer variable onto stack
il.Emit(OpCodes.Call, intToString); //call tostring for age, "44" on stack now
il.Emit(OpCodes.Ret); //return "44"
var agestr = (Func<Item, string>)dm.CreateDelegate(typeof(Func<Item, string>));
Console.WriteLine(agestr.Invoke(new Item()));
现在它可以工作了。