繁体   English   中英

与代表有关的 params 修饰符与 out 和 ref 修饰符之间的区别

[英]Difference between params modifier and out and ref modifiers with regards to delegates

//Main method
test6 _300er = new(yetan.aa);
        _300er.Invoke(45, 78);

        test7 _200lr = new(yetan.bb);
        _200lr.Invoke(new int[4]);

        test8 max8 = new(yetan.dd);
        double rty = 45;
        max8.Invoke(ref rty);
        test9 max9 = new(yetan.cc);
        max9.Invoke(78);

        test10 neo1 = new(yetan.ee);
        neo1.Invoke(out char ytss);
        test11 neo2 = new(yetan.ff);
        neo2.Invoke('^');


delegate void test6(params int[] h);
delegate void test7(int[] h);
delegate void test8(ref double j);
delegate void test9(double j);
delegate void test10(out char j);
delegate void test11(char j);

class yetan {

    public static void aa(int[] y) {
        Console.WriteLine("params dude");
    }

    public static void bb(params int[] y) {
        Console.WriteLine("params dude");
    }
    public static void cc(double y) {
        Console.WriteLine("jhjgbrvf");
    }
    public static void dd(ref double y) {
        Console.WriteLine("jhjgbrvf");
    }
    public static void ee(out char y) {
        y = '%';
        Console.WriteLine("vvvvvvv");
    }
    public static void ff(char y) {
        Console.WriteLine("vvvvvv");
    }

}

我用 params、out、ref 修饰符声明了一个 delagate,但没有
并创建了与委托人签名相对应的方法
我注意到,如果我可以将具有 params 修饰符的 delagte test6还没有 parmas 修饰符的方法aa它仍然可以工作,最后参数将方法aa的行为就像它具有 params 修饰符一样。
反之亦然,但最后由委托决定它指向的方法是否具有 params 修饰符
但由于某种原因,修饰符outref并非如此
如果我的委托test8没有指定 ref 它的实例将无法指向方法dd

你能告诉我这背后的原因是什么吗?

因为params数组仍然是一个常规数组,但为调用站点添加了语法糖。 然而outref改变了方法的行为(值需要从方法中复制出来)。

换句话说:您可以使用真实数组调用params方法,但不能使用值文字调用outref方法(仅使用变量)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM