简体   繁体   English

委托示例有什么意义

[英]Delegate example what's the point

Like many other posts I've found on SO, I'm trying to get my head around delegates. 像我在SO上找到的许多其他帖子一样,我正在努力吸引代表们的注意。 Hopefully this example is not classed a duplicate because I am asking a specific question about a particular example. 希望该示例不会被归类为重复示例,因为我正在询问有关特定示例的特定问题。

 public delegate void HelloFunctionDelegate(string message);

    public class Delegate
    {
        static void Main()
        {
            HelloFunctionDelegate del = new HelloFunctionDelegate(GoodNight); // delegate will point to the GoodNight method

            del("Hello"); // invoke the delegate
        }

        public static void GoodMorning(string strMessage)
        {
            Console.WriteLine(strMessage + " and good morning!");
            Console.ReadKey();
        }

        public static void GoodNight(string strMessage)
        {
            Console.WriteLine(strMessage + " and good night!");
            Console.ReadKey();
        }
    }

So in my example I understand that my delegate is a reference to any function that matches its signature and if I pass in GoodMorning I will see: Hello and good morning! 因此,在我的示例中,我理解我的委托是对与其签名匹配的任何函数的引用,如果我传入GoodMorning,我将看到: Hello and good morning!

and if I pass in GoodNight I will see: Hello and good night! 如果我通过晚安,我会看到: Hello and good night!

So its kind of like going through a middle man... 所以这就像经历一个中间人...

I don't understand is what's the point, why wouldn't I just directly call my GoodMorning / GoodNight methods as and when I need to use them? 我不明白这是什么意思,为什么在需要使用它们时不直接调用我的GoodMorning / GoodNight方法呢?

Maybe there are better examples for when a delegate is useful, but in this example, why don't I just bypass the middle man? 也许有更好的例子说明委托何时有用,但是在这个例子中,为什么我不绕过中间人呢?

Since you are asking concretely about this example and not in general: There is no point to doing that in this particular piece of code. 因为您是在具体地询问此示例,而不是一般性的问题,所以:在此特定代码段中没有必要这样做。 It teaches you the mechanics of delegates but it does not teach you the point of using them. 它教会了您代表的机制,但没有教会您使用代表的意义。

In short, the point is that some piece of code can take a reference to a method without knowing what method it will actually receive. 简而言之,关键是某些代码段可以引用某个方法,而无需知道它将实际接收哪种方法。 It can later call that delegate at will. 以后可以随意呼叫该代表。 That enables more abstractions than otherwise possible. 这样可以实现更多的抽象。

Consider you have the following delegate: 考虑您具有以下代表:

public delegate void CarEvent(Car car);

And then you have an implementation like the following: 然后,您将实现如下所示的实现:

public class Car : DataRecord
{
    // An event to execute when the record is deleted
    public CarEvent OnDelete { get; set; }

    public void Delete()
    {
        this.DeleteRecord(); // Deletes this record from ex. the database

        if (OnDelete)
        {
            OnDelete(this); // Executes the event
        }
    }
}

By using a delegate you can subscribe different methods to the OnDelete allowing you to do different things when the record is deleted. 通过使用委托,您可以为OnDelete预订不同的方法,从而在删除记录时可以做不同的事情。

Ex. 防爆。 you can make it so when the record is deleted it's deleted from a "ListView" that holds it. 您可以这样做,以便在删除记录时将其从保存该记录的"ListView"中删除。

public class CarList : ListView
{
    public CarList()
        : base()
    {
        foreach (var car in CarRecords.LoadCars())
        {
            var listViewItem = new ListViewItem(car);
            car.OnDelete = this.DeleteCarFromList;

            this.Items.Add(listViewItem);
        }
    }

    private void DeleteCarFromList(Car deletedCar)
    {
        this.Items.Remove(deletedCar);
    }
}

Of course the above is a rough example and there is a lot more things and different kind of situations where you can use delegates and most notably if you want to use them for events you should consider implementing them using the event keyword. 当然,以上只是一个粗糙的示例,还有很多事情和不同类型的情况,您可以使用委托,并且最显着的是,如果您想将它们用于事件,则应考虑使用event关键字实现它们。 - https://msdn.microsoft.com/en-us/library/awbftdfh.aspx -https://msdn.microsoft.com/en-us/library/awbftdfh.aspx

All in all you want to use delegates when the behavior may differ depending on the overall implementation of something. 当行为可能会有所不同时,您总要使用委托,具体取决于整体的实现。 Like you might want to do one thing in one situation and something else in another situation, but they should both over-all do the same thing. 就像您可能想在一种情况下做一件事情而在另一种情况下做别的事情一样,但是他们俩都应该共同做同样的事情。

If you do not need different behaviors based on implementation then there's no need to use delegates. 如果您不需要基于实现的不同行为,则无需使用委托。 You'd always want to call a method directly if possible. 如果可能的话,您总是想直接调用一个方法。

I hope this explained it okay. 我希望这可以解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM