简体   繁体   English

委托和事件:C#

[英]Delegate and Event : C#

I've got a question on events and delegates in C#.我有一个关于 C# 中的事件和委托的问题。 I saw in many codes that they've used the event and delegate keyword to create an event trigger.我在许多代码中看到他们使用eventdelegate关键字来创建事件触发器。 Let's skip that for now, what concerned me a lot was the functions that the event triggered or rather the functions that were invoked here is the scope snippet.让我们暂时跳过它,我最关心的是事件触发的函数,或者更确切地说,这里调用的函数是作用域片段。

public delegate void EventHandler();
class Program
{
    //Note : Assigning the evet to the delegate
    public static event EventHandler _show;

    static void Main(string[] args)
    {
        _show += new EventHandler(Dog);
        _show += new EventHandler(Cat);
        _show.Invoke();                   
    }

    static void Dog() {
        Console.WriteLine("Doggie");
    }

    static void Cat(){
        Console.WriteLine("Pussy");
    }

}

` `

As you can see there are several functions called Dog / Cat.如您所见,有几个函数称为 Dog / Cat。 There return types are void but when you execute it looks like a string value is returned to the event _show .返回类型是void但当您执行它时,它看起来像一个string值返回给事件_show Can someone explain whats going on here?有人可以解释这里发生了什么吗?

You are interpreting the syntax wrongly.您错误地解释了语法。

static void Main(string[] args)
    {
        _show += new EventHandler(Dog);
        _show += new EventHandler(Cat);
        _show.Invoke();                   
    }

The _show += new EventHandler(Dog) will just queue the function call of Dog() . _show += new EventHandler(Dog)只会将Dog()的函数调用_show += new EventHandler(Dog)队列。 So its like holding all the function calls in a queue and then executing them in FIFO order.所以它就像将所有函数调用保存在一个队列中,然后以 FIFO 顺序执行它们。

You are not returning anything here.你不会在这里返回任何东西。 Only all of your functions are getting called sequentially and then values are getting printed.只有您的所有函数都被顺序调用,然后值被打印出来。

The show Event just run the Dog and then run Cat Methods. show Event 只运行Dog ,然后运行Cat方法。 Obviously, it will print "Doggie" and "Pussy".显然,它会打印“Doggie”和“Pussy”。

If you want to return a string:如果你想返回一个字符串:

static string Dog() {
       // Console.WriteLine("Doggie");
       return "Doggie";
}

and change the delegate decalre:并更改delegate贴花:

public delegate string EventHandler();

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

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