代表和活动:C#

时间:2014-04-19 04:31:08

标签: c# c++ .net c#-4.0

我对C#中的事件和代表有疑问。我在许多代码中看到他们使用eventdelegate关键字来创建事件触发器。让我们暂时跳过这个问题,关注我的是事件触发的函数,或者这里调用的函数是范围片段。

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");
    }

}

`

正如您所看到的,有几种叫做Dog / Cat的功能。返回类型为void但是当您执行时,看起来string值会返回到事件_show。有人能解释一下这里发生了什么吗?

2 个答案:

答案 0 :(得分:0)

您正在错误地解释语法。

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

_show += new EventHandler(Dog)只会对Dog()的函数调用进行排队。因此它就像将所有函数调用保存在队列中,然后按FIFO顺序执行它们。

你没有在这里归还任何东西。只有所有函数按顺序调用,然后才会打印值。

答案 1 :(得分:0)

show事件只运行Dog,然后运行Cat方法。显然,它将打印" Doggie"和" Pussy"。

如果你想返回一个字符串:

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

并更改delegate decalre:

public delegate string EventHandler();