C# 语言允许事件使用任何委托类型,但 .NET Framework 对委托和事件有更严格的准则。如果打算将您的组件与“.NET Framework”一起使用,您可能希望遵守这些指南。
.NET Framework 指南指示用于事件的委托类型应采用两个参数:“对象源”参数(用于指示事件源)和特定于事件的参数(它封装有关事件的其他任何信息)。特定于事件的参数应从
下面的示例与如何:创建响应事件的控件(C# 编程指南)中的代码类似,区别在于此版本遵循 .NET Framework 准则。
示例
| C# | 复制代码 |
|---|---|
namespace TestCollections
{
// A class that works just like ArrayList, but sends event
// notifications whenever the list changes:
public class ListWithChangedEvent : System.Collections.ArrayList
{
// An event that clients can use to be notified whenever the
// elements of the list change:
public event System.EventHandler Changed;
// Invoke the Changed event; called whenever list changes:
protected virtual void OnChanged(System.EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
// Override some of the methods that can change the list;
// invoke event after each:
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(System.EventArgs.Empty);
return i;
}
public override void Clear()
{
base.Clear();
OnChanged(System.EventArgs.Empty);
}
public override object this[int index]
{
set
{
base[index] = value;
OnChanged(System.EventArgs.Empty);
}
}
}
}
namespace TestEvents
{
using TestCollections;
class EventListener
{
private ListWithChangedEvent m_list;
public EventListener(ListWithChangedEvent list)
{
m_list = list;
// Add "ListChanged" to the Changed event on m_list:
m_list.Changed += new System.EventHandler(ListChanged);
}
// This will be called whenever the list changes:
private void ListChanged(object sender, System.EventArgs e)
{
System.Console.WriteLine("This is called when the event fires.");
}
public void Detach()
{
// Detach the event and delete the list:
m_list.Changed -= new System.EventHandler(ListChanged);
m_list = null;
}
}
class Test
{
// Test the ListWithChangedEvent class:
static void Main()
{
// Create a new list:
ListWithChangedEvent list = new ListWithChangedEvent();
// Create a class that listens to the list's change event:
EventListener listener = new EventListener(list);
// Add and remove items from the list:
list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}
| |
输出
This is called when the event fires. This is called when the event fires. | |