无法理解多播委托 [英] Unable to understand multicast delegates

查看:73
本文介绍了无法理解多播委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅我的计划以了解我的问题。请不要指导我到msdn或任何文章谢谢



Please refer my program to understand my question. Please dont guide me to msdn or any articles thank you

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delgates_Ex1
{

    public delegate void ExampleDelgate(int x, int y);


    class Democlass
    {
        public void Add(int x, int y)
        {

            Console.WriteLine(x+y);
            

        }


        public static void mul(int x, int y)
        {
            Console.WriteLine(x*y);

        }

    }


    class Program
    {
        public static void Sub(int x, int y)
        {

            Console.WriteLine(x -y);


        }



        static void Main(string[] args)
        {
            Democlass d = new Democlass();

            ExampleDelgate e1 = new ExampleDelgate(d.Add);  // I know here I am doing  instantiation of the delegate

            ExampleDelgate e2 = new ExampleDelgate(Democlass.mul);

            ExampleDelgate e3 = e1 + e2;


            e3 = e1 + e2 + e3;  // When I execute the line i get twice i.e out put would be  30 200 30 200 can any one explain me what is happening here. Basically I am trying to
            //understand Mutlicast delegates and when i remove +e3 i just get only once


            e3(20, 10);  // and here I am doing Delegate Invocation

        }
    }
}

推荐答案

1。 ExampleDelgate e3 = e1 + e2; 创建一个委托对象e3作为e1和e2的总和,这类似于添加到event两种方法,在本例中是列表将有接下来的两种方法:添加 mul



所以如果你要调用 e3(20,10); ==>将执行两种方法添加(20,10) mul(20,10)。你会得到结果: 30,200



2.如果加上额外的行: e3 = e1 + e2 + e3; 这相当于: e3 + = e1 + e2; ==>方法列表将变为:添加 mul 添加 mul



所以如果你要调用 e3(20,10) ; ==>将执行4种方法==> 30,200,30,2
1. ExampleDelgate e3 = e1 + e2; create an delegate object e3 as sum of e1 and e2 this is similar with the adding into an "event" two methods, in this case the list will have the next 2 methods: Add and mul.

So if you will invoke e3(20, 10); ==> both methods Add(20, 10) and mul(20,10) will be executed. and you will have the results: 30 , 200

2. If you add the extra line: e3 = e1 + e2 + e3; this is equivalent with: e3+= e1 +e2; ==> the list of methods will become: Add , mul, Add , mul.

So if you will invoke e3(20, 10); ==> 4 methods will be executed ==> 30, 200, 30, 200


这篇关于无法理解多播委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆