加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用组播委托链接功能

发布时间:2020-12-15 03:43:35 所属栏目:百科 来源:网络整理
导读:我的问题在下面的代码中详细说明 – 我问的原因是我正在尝试代理: //create the delegate delegate int del(int x);class Program { static void Main(string[] args) { Program p; p = new Program(); del d = p.a; d += p.b; d += p.c; d += p.d; d += p.
我的问题在下面的代码中详细说明 – 我问的原因是我正在尝试代理:
//create the delegate          
delegate int del(int x);

class Program {


    static void Main(string[] args) {

        Program p;
        p = new Program();

        del d = p.a;
        d += p.b;
        d += p.c;
        d += p.d;
        d += p.e;
        Console.WriteLine(d(10)); //<<was hoping it would be 10+2+3+4+5+6

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }

    private int a(int x) { Console.WriteLine("a is called"); return x + 2; }
    private int b(int x) { Console.WriteLine("b is called"); return x + 3; }
    private int c(int x) { Console.WriteLine("c is called"); return x + 4; }
    private int d(int x) { Console.WriteLine("d is called"); return x + 5; }
    private int e(int x) { Console.WriteLine("e is called"); return x + 6; }

}

16返回….

所有的功能都会触发,因为各种消息“a被调用”等都被打印到控制台,但只返回从上一个函数e返回的数量 – 我假设在后台他们被返回,但是被覆盖?

解决方法

当您的问题中有一个多播代理(如d)时,返回值是d的调用列表的最后一个方法的返回值.

一般来说,对于多播代理,使用返回类型void是最自然的.

编译器没有机会猜到你希望10 2 3 4 5 6.你没有在任何地方指定它.

您可以将代理类型更改为:

delegate void del(int xToAdd,ref int sum);

那么你的方法a,例如,应该是这样的:

private void a(int x,ref int sum) { Console.WriteLine("a is called"); sum += x + 2; }

然后,多播代理实例d将被调用:

int sum = 0;
d(10,ref sum);
Console.WriteLine(sum);

我希望这有帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读