通过ref将函数传递给委托是否有区别?

时间:2017-01-27 07:44:30

标签: c# reference delegates ref

我遇到了一段使用委托的C#代码,并通过引用将该函数传递给委托......

        delegate bool MyDel(int x);
        static bool fun(int x) {
            return x < 0;
        }
        public static void Main() {
            var d1 = new MyDel(fun);       // what I usually write
            var d2 = new MyDel(ref fun);   
        }

编译器没有抱怨并且很好地构建了项目。在运行一些测试用例时我没有发现任何差异,这种语法与通常的语法有什么不同?

更新

正如 InBetween 所提到的,似乎这种语法也是有效的(而且它更没意义)

var d3 = new MyDel(out fun);

1 个答案:

答案 0 :(得分:1)

看来,在这种情况下,通过ref / out / normal-way传递没有区别, 我试着看看ILDASM是否有任何区别,但没有区别......

 delegate void MyDel();
 static void Main(string[] args)
    {
        MyDel myDel = new MyDel(Mtd1);
        MyDel d3 = new MyDel(ref Mtd1);
        MyDel d1 = new MyDel(ref Mtd2);
        MyDel d2 = new MyDel(out Mtd3);
    }

enter image description here