使用C#中的代表(或其他语言)的或其他、语言、代表

2023-09-04 02:11:53 作者:心碎见蓝天

我一直想代表如何可能是有用的,为什么我们应使用它们?其他则是类型安全,并在Visual Studio文档所有这些优势,什么是现实世界中使用委托的。

I have always wondered how delegates can be useful and why shall we use them? Other then being type safe and all those advantages in Visual Studio Documentation, what are real world uses of delegates.

我已经找到了一个,这是非常有针对性的。

I already found one and it's very targeted.

using System;

namespace HelloNamespace {

    class Greetings{
    public static void DisplayEnglish() {
            Console.WriteLine("Hello, world!");
    }
    public static void DisplayItalian() {
             Console.WriteLine("Ciao, mondo!");
    }
    public static void DisplaySpanish() {
             Console.WriteLine("Hola, imundo!");
         }
    }

    delegate void delGreeting();

    class HelloWorld {
        static void Main(string [] args) {

    int iChoice=int.Parse(args[0]);
    delGreeting [] arrayofGreetings={
             new delGreeting(Greetings.DisplayEnglish),
             new delGreeting(Greetings.DisplayItalian),
             new delGreeting(Greetings.DisplaySpanish)};

    arrayofGreetings[iChoice-1]();
         }
    }
}

不过,如果... {}解析的说法,这并不表明我到底使用委托,而不是有条件的优点和运行的方法。

But this doesn't show me exactly the advantages of using delegates rather than a conditional "If ... { }" that parses the argument and run the method.

有谁知道为什么它的更好的使用委托在这里,而不是如果... {}。另外你有演示代表的实用性其他例子。

Does anyone know why it's better to use delegate here rather than "if ... { }". Also do you have other examples that demonstrate the usefulness of delegates.

谢谢!

推荐答案

最常见的真实世界的日常使用代表,我能想到的在C#是事件处理。当你有一个WinForm的一个按钮,你想要做的事是单击该按钮时,那么你最终注册一个委托函数被它被点击时按钮命名为你做的是什么。

The most common real-world everyday use of delegates that I can think of in C# would be event handling. When you have a button on a WinForm, and you want to do something when the button is clicked, then what you do is you end up registering a delegate function to be called by the button when it is clicked.

这一切都发生自动为您在身后由Visual Studio本身产生的code中的场景,所以你可能看不到它发生在哪里。

All of this happens for you automatically behind the scenes in the code generated by Visual Studio itself, so you might not see where it happens.

一个真实的案例,可能是更有用,你是,如果你想使人们可以使用,将读取的数据从互联网饲料库,而当饲料已经更新通知他们。通过使用委托,那么谁在使用你的库的程序员将能够有一个名为每当饲料更新自己的code。

A real-world case that might be more useful to you would be if you wanted to make a library that people can use that will read data off an Internet feed, and notify them when the feed has been updated. By using delegates, then programmers who are using your library would be able to have their own code called whenever the feed is updated.