代表们的目的是什么?他们的优势是什么?

时间:2015-08-17 13:18:01

标签: c# delegates console-application

有人可以向我解释为什么我们需要代表,他们有什么好处?

这是一个我使用和不使用委托创建的简单程序(使用普通方法):

没有代表的节目:

namespace Delegates
{
    class Program
    {
        static void Main(string[] args)
        {
            abc obj = new abc();

            int a = obj.ss1(1, 2);
            int b = obj.ss(3,4);

            Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);

            Console.ReadKey();
        }
    }

    class abc
    {
        public int ss(int i, int j)
        {
            return i * j;
        }

        public int ss1(int x, int y)
        {
            return x + y;
        }
    }
}

与代表合作:

namespace Delegates
{
    public delegate int my_delegate(int a, int b);

    class Program
    {    
        static void Main(string[] args)
        {
            my_delegate del = new my_delegate(abc.ss);    
            abc obj = new abc();

            my_delegate del1 = new my_delegate(obj.ss1);

            int a = del(4, 2);    
            int b = del1(4, 2);

            Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
            Console.ReadKey();    
        }    
    }

    class abc
    {    
        public int ss(int i, int j)
        {    
            return i * j;    
        }

        public int ss1(int x, int y)
        {    
            return x + y;    
        }    
    }    
}

两个程序都给出相同的结果,那么使用Delegates的优势是什么?

感谢。

1 个答案:

答案 0 :(得分:2)

委托旨在使用event-driven方法进行编程,从而创建更强大的解耦源代码

通过代表,我们可以创建类似publisher-subscriber pattern的内容,订阅者可以注册接收来自发布商的活动。

我们通常会将代理人视为事件处理程序。例如,对于委托,我们可以通过在事件发生时调度事件来创建可重用控件(例如:click事件,...),在这种情况下,控件是发布者,任何对处理此事件感兴趣的代码(订阅者)都将注册控件的处理程序。

这是代表们的主要好处之一。

@LzyPanda在这篇文章中指出了更多的用法:When would you use delegates in C#?

相关问题