微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我的问题在下面的代码中详细说明 – 我问的原因是我正在尝试代理:
//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);

我希望这有帮助.

原文地址:https://www.jb51.cc/csharp/93930.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐