日期:2014-05-18  浏览次数:20804 次

C#委托和事件

委托和事件

.NET Framework 还可以广泛地将委托用于事件处理任务,如 Windows 或 Web 应用程序中的按钮 Click 事件。Java 中的事件处理通常通过实现自定义侦听器类完成,而 C# 开发人员则可以利用委托处理事件。事件的声明类似于具有委托类型的字段,区别在于事件声明前面有 event 关键字。事件通常被声明为 public,但允许使用任何可访问性修饰符。下面的示例演示了 delegateevent 的声明。

C#? “复制”图像复制代码
// Declare the delegate type:
public delegate void CustomEventHandler(object sender, System.EventArgs e);

// Declare the event variable using the delegate type:
public event CustomEventHandler CustomEvent;

事件委托是多路广播的,这意味着它们可以对多个事件处理方法进行引用。通过维护事件的已注册事件处理程序列表,委托为引发事件的类担当事件发送器的角色。下面的示例演示如何为多个函数订阅事件。EventClass 类包含委托、事件和调用事件的方法。请注意调用事件只能从声明该事件的类内部进行。然后,TestEvents 类使用 += 运算符订阅事件,并使用 -= 运算符取消订阅。调用 InvokeEvent 方法时,它将激发事件,所有订阅了该事件的函数也同步激发,如下面的示例所示。

C#? “复制”图像复制代码
public class EventClass
{
    // Declare the delegate type:
    public delegate void CustomEventHandler(object sender, System.EventArgs e);

    // Declare the event variable using the delegate type:
    public event CustomEventHandler CustomEvent;

    public void InvokeEvent()
    {
        // Invoke the event from within the class that declared the event:
        CustomEvent(this, System.EventArgs.Empty);
    }
}

class TestEvents
{
    private static void CodeToRun(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("CodeToRun is executing");
    }

    private static void MoreCodeToRun(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("MoreCodeToRun is executing");
    }

    static void Main()
    {
        EventClass ec = new EventClass();

        ec.CustomEvent += new EventClass.CustomEventHandler(CodeToRun);
        ec.CustomEvent += new EventClass.CustomEventHandler(MoreCodeToRun); 

        System.Console.WriteLine("First Invocation:");
        ec.InvokeEvent();

        ec.CustomEvent -= new EventClass.CustomEventHandler(MoreCodeToRun);

        System.Console.WriteLine("\nSecond Invocation:");
        ec.InvokeEvent();
    }
}

输出

First Invocation:

CodeToRun is executing

MoreCodeToRun is executing

?

Second Invocation:

CodeToRun is executing