【问题标题】:What is the point of using static modifier when creating an EventHandler? [duplicate]创建 EventHandler 时使用 static 修饰符有什么意义? [复制]
【发布时间】:2016-04-24 20:24:07
【问题描述】:

考虑以下来自dotnetperls 的示例:

using System;

public delegate void EventHandler();

class Program
{
    public static event EventHandler _show;

static void Main()
{
// Add event handlers to Show event.
_show += new EventHandler(Dog);
_show += new EventHandler(Cat);
_show += new EventHandler(Mouse);
_show += new EventHandler(Mouse);

// Invoke the event.
_show.Invoke();
}

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

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

static void Mouse()
{
Console.WriteLine("Mouse");
}
}

使用静态修饰符有什么意义?

【问题讨论】:

  • 因为你从静态方法中使用它 - static void Main()

标签: c# eventhandler


【解决方案1】:

由于您是从静态方法 (Main) 进行事件订阅,因此您可以直接使用静态方法作为事件处理程序。

否则你需要一个类的实例:

using System;

public delegate void EventHandler();

class Program
{
    public static event EventHandler _show;

    static void Main()
    {
        var program = new Program();

        _show += new EventHandler(program.Dog);
        _show += new EventHandler(program.Cat);
        _show += new EventHandler(program.Mouse);
        _show += new EventHandler(program.Mouse);

        // Invoke the event.
        _show.Invoke();
    }

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

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

    void Mouse()
    {
        Console.WriteLine("Mouse");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2015-11-08
    • 2011-08-13
    • 2023-03-31
    • 2016-12-11
    • 2014-05-12
    • 2011-11-08
    相关资源
    最近更新 更多