自定义事件,泛型

来源:互联网 发布:飞客数据恢复中心 编辑:程序博客网 时间:2024/05/29 15:13
C#  CopyCode image复制代码
// This example demonstrates the EventHandler<T> delegate.

using System;
using System.Collections.Generic;

//---------------------------------------------------------
public class MyEventArgs : EventArgs
{
private string msg;

public MyEventArgs( string messageData ) {
msg = messageData;
}
public string Message {
get { return msg; }
set { msg = value; }
}
}
//---------------------------------------------------------
public class HasEvent
{
// Declare an event of delegate type EventHandler of
// MyEventArgs.

public event EventHandler<MyEventArgs> SampleEvent;

public void DemoEvent(string val)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<MyEventArgs> temp = SampleEvent;
if (temp != null)
temp(this, new MyEventArgs(val));
}
}
//---------------------------------------------------------
public class Sample
{
public static void Main()
{
HasEvent he = new HasEvent();
he.SampleEvent +=
new EventHandler<MyEventArgs>(SampleEventHandler);
he.DemoEvent("Hey there, Bruce!");
he.DemoEvent("How are you today?");
he.DemoEvent("I'm pretty good.");
he.DemoEvent("Thanks for asking!");
}
private static void SampleEventHandler(object src, MyEventArgs mea)
{
Console.WriteLine(mea.Message);
}
}
//---------------------------------------------------------
/*
This example produces the following results:

Hey there, Bruce!
How are you today?
I'm pretty good.
Thanks for asking!

*/

使用 Visual C# 在运行时创建事件处理程序

  1. 创建 EventHandler 委托的一个实例,并向其传递要绑定到的方法的地址。

  2. 将该委托对象添加到引发此事件时所调用的方法的列表中。

    下面的代码示例演示如何将 Button1 控件的 Click 事件绑定到名为 myEventHandler 的方法:

    C#  CopyCode image复制代码
    Button1.Click += new System.EventHandler(this.myEventHandler);

 
原创粉丝点击