这个委托在main方法中的目的是什么?

时间:2019-01-10 19:13:38

标签: c# delegates

我正在学习代表。这是C#上的LinkedIn教程的示例代码(第一个)。我无法确定使用委托的好处和目的。目前尚不清楚是什么原因导致我们不会直接调用该函数。我重新输入了自己的代码(第二个),看起来似乎也得到了类似的结果。

namespace Delegates1._10._2018

{
    public delegate string MyDelegate(int arg1, int arg2);

    internal class Program
    {  
        static string func1(int a, int b)
        {
            return (a + b).ToString();
        }

        static string func2(int a, int b)
        {
            return (a * b).ToString();
        }

        static void Main(string[] args)
        {
            MyDelegate f = func1;
            Console.WriteLine("The number is: " + f(10,20));
            f = func2;
            Console.WriteLine("The number is: " + f(10,20));
        }
    }
}



internal class Program
    {
        public static int func1(int a, int b)
        {
            return (a + b);
        }
        public static int func2(int a, int b)
        {
            return (a * b);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("The number is: " + func1(10, 20));
            Console.WriteLine("The number is: " + func2(10, 20));
        }
    }

数字是:30 数字是:200

2 个答案:

答案 0 :(得分:2)

委托只是声明方法的形状(public delegate string MyDelegate(int arg1, int arg2);。您可以更改第一个Main方法中显示的方法。这是一个人为的示例,没有因为它不处理外部数据或输入来操纵行为,所以有很多好处。

答案 1 :(得分:0)

这个例子很糟糕!。让我尝试解释一下:

我们有一辆普通汽车,汽车不知道如何自行驾驶,坐在汽车中的人也知道如何驾驶。所以汽车问人(代表)开我!

public delegate int DriveMeWithSpeed(int maxForceOnPedal);
    public class Car
    {
        DriveMeWithSpeed speedy;

        public Car(DriveMeWithSpeed YourSpeed)
        {
            speedy = YourSpeed;
        }

        public void Drive()
        {
            if (speedy != null) speedy(100);
        }

    }
    public class Person
    {
        public int IDrive(int PedalForce)
        {
            return 40;
        }
    }

    public static void Main(string[] args)
        {
            Person Me = new Person();

            Car myCar = new Car(Me.IDrive);
            myCar.Drive();
        }

所以主要概念是类本身并不总是知道函数的功能,因此将其委托给知道该做什么的类。