代码之家  ›  专栏  ›  技术社区  ›  Lasse V. Karlsen

动态方法和输出参数?

  •  8
  • Lasse V. Karlsen  · 技术社区  · 15 年前

    如何为具有 out -参数,像这样?

    public delegate void TestDelegate(out Action a);
    

    假设我只需要一个方法来设置 a 论证 null 当我调用方法时。

    请注意,我知道处理此问题的更好方法是使方法返回 Action 委托,但这只是一个大型项目的简化部分,并且所讨论的方法已经返回了一个值,我需要处理 外面的 除参数外,还有一个问题。

    我试过这个:

    using System;
    using System.Text;
    using System.Reflection.Emit;
    
    namespace ConsoleApplication8
    {
        public class Program
        {
            public delegate void TestDelegate(out Action a);
    
            static void Main(String[] args)
            {
                var method = new DynamicMethod("TestMethod", typeof(void),
                    new Type[] { typeof(Action).MakeByRefType() });
                var il = method.GetILGenerator();
    
                // a = null;
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Starg, 0);
    
                // return
                il.Emit(OpCodes.Ret);
    
                var del = (TestDelegate)method.CreateDelegate(typeof(TestDelegate));
                Action a;
                del(out a);
            }
        }
    }
    

    但是,我得到了:

    VerificationException was unhandled:
    Operation could destabilize the runtime.
    

    del(out a); 线。

    请注意,如果我注释掉在堆栈上加载空值的两行,并尝试将其存储到参数中,那么该方法运行时没有异常。


    编辑 :这是最好的方法吗?

    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldnull);
    il.Emit(OpCodes.Stind_Ref);
    
    1 回复  |  直到 15 年前
        1
  •  9
  •   Sam Harwell    15 年前

    out 争论只是 ref 与…争论 OutAttribute 应用于参数。

    要存储到by-ref参数,需要使用 stind 操作码,因为参数本身是指向对象实际位置的托管指针。

    ldarg.0
    ldnull
    stind.ref
    
    推荐文章