jeudi 11 octobre 2018

C# dynamic method: return string representation of integer

I want to create dynamic method which takes Int32 parameter and returns string representation of it:

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); //have age 44 on stack
    il.Emit(OpCodes.Call, intToString); //call tostring for age, as a result "44" will be pushed onto stack
    il.Emit(OpCodes.Ret); //return "44"
    var agestr = (Func<Item, string>)dm.CreateDelegate(typeof(Func<Item, string>));
    Console.WriteLine(agestr.Invoke(new Item()));
}

But the method fails with exception Object reference not set to an instance of an object. What I missed?





Aucun commentaire:

Enregistrer un commentaire