Creating method dynamically, and executing it

后端 未结 6 1198
轮回少年
轮回少年 2020-12-23 22:42

Background:

I want to define few static methods in C# , and generate IL code as byte array, from one of these methods, selected at runt

6条回答
  •  心在旅途
    2020-12-23 23:37

    I think the problem is to do with using IL from one type/assembly in an another. If you replace this:

    mb.CreateMethodBody(il, il.Count());
    

    with this:

    ILGenerator generator = mb.GetILGenerator();
    generator.Emit(OpCodes.Ldarg_0);
    generator.Emit(OpCodes.Ldarg_1);
    generator.Emit(OpCodes.Mul);
    generator.Emit(OpCodes.Ret);
    

    then it will execute the method correctly (no Console.WriteLine, but it returns the right value).

    If you really need to be able to slurp IL from an existing method, you'll need to look further - but if you just needed validation that the rest of the code was working, this may help.

    One thing that you may find interesting is that the error changes in your original code if you take out the Console.WriteLine call from Experiment. It becomes an InvalidProgramException instead. I've no idea why...

提交回复
热议问题