Skip to main content
 首页 » 编程设计

c#之当我尝试使用 DynamicMethod 创建始终返回 true 的方法时出现错误

2024年02月13日14三少

今天,我开始学习 DynamicMethod 类。出于学习目的,我着手使用 DynamicMethod 创建一个不带参数且始终返回 bool 值 true 的函数。

我在 C# 中创建了一个函数来执行此操作,然后使用 Telerik JustDecompile 检查生成的 IL 代码。

.method public hidebysig instance bool ReturnTrue1 () cil managed  
{ 
    .locals init ( 
        [0] bool CS$1$0000 
    ) 
 
    IL_0000: nop 
    IL_0001: ldc.i4.1 
    IL_0002: stloc.0 
    IL_0003: br.s IL_0005 
 
    IL_0005: ldloc.0 
    IL_0006: ret 
} 

看起来很简单。根据文档,看起来这些指令只是将一个整数 1 放在要返回的堆栈上。

根据我看过的一些示例,我编写了以下控制台应用程序。

using System; 
using System.Reflection.Emit; 
 
namespace EntityFrameworkDynamicMethod 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        {             
            ReturnTrue ReturnTrueDelegate = GetReturnTrueDelegate(); 
            ReturnTrueDelegate();             
        }         
 
        delegate bool ReturnTrue(); 
 
        static ReturnTrue GetReturnTrueDelegate() 
        {             
            DynamicMethod method = new DynamicMethod("ReturnTrue", typeof(bool), new Type[] {}); 
            ILGenerator generator = method.GetILGenerator(); 
            Label IL_0005 = generator.DefineLabel(); 
            generator.Emit(OpCodes.Nop); 
            generator.Emit(OpCodes.Ldc_I4_1); 
            generator.Emit(OpCodes.Stloc_0);             
            generator.Emit(OpCodes.Ldloc_0, IL_0005);             
            generator.MarkLabel(IL_0005); 
            generator.Emit(OpCodes.Ret); 
 
            return (ReturnTrue)method.CreateDelegate(typeof(ReturnTrue)); 
        } 
    } 
} 

但是,当我运行这段代码时,在 ReturnTrueDelegate();

上引发了以下异常
System.Security.VerificationException: Operation could destabilize the runtime. 
at ReturnTrue() 

这个异常是什么意思,我该怎么做才能解决这个问题?

请您参考如下方法:

generator.Emit(OpCodes.Ldloc_0, IL_0005); 

这是不正确的; ldloc.0 指令没有参数(您是说 br.s 吗?)。
您也不能在不声明的情况下使用本地 0。

但是,您不需要这些;您需要做的就是加载 1 (ldc.i4.1) 并返回它 (ret)。
如果反编译 Release模式代码,您应该会看到。