accessor-declarations 的一种用法是公开大量的事件但不为每个事件分配字段,而是使用字典来存储这些事件实例。这只有在具有非常多的事件、但您预计大部分事件都不会实现时才有用。
示例
C# | 复制代码 |
---|
public delegate void Delegate1(int i);
public delegate void Delegate2(string s);
public class PropertyEventsSample
{
private System.Collections.Generic.Dictionary<string, System.Delegate> eventTable;
public PropertyEventsSample()
{
eventTable = new System.Collections.Generic.Dictionary<string, System.Delegate>();
eventTable.Add("Event1", null);
eventTable.Add("Event2", null);
}
public event Delegate1 Event1
{
add
{
eventTable["Event1"] = (Delegate1)eventTable["Event1"] + value;
}
remove
{
eventTable["Event1"] = (Delegate1)eventTable["Event1"] - value;
}
}
public event Delegate2 Event2
{
add
{
eventTable["Event2"] = (Delegate2)eventTable["Event2"] + value;
}
remove
{
eventTable["Event2"] = (Delegate2)eventTable["Event2"] - value;
}
}
internal void FireEvent1(int i)
{
Delegate1 D;
if (null != (D = (Delegate1)eventTable["Event1"]))
{
D(i);
}
}
internal void FireEvent2(string s)
{
Delegate2 D;
if (null != (D = (Delegate2)eventTable["Event2"]))
{
D(s);
}
}
}
public class TestClass
{
public static void Delegate1Method(int i)
{
System.Console.WriteLine(i);
}
public static void Delegate2Method(string s)
{
System.Console.WriteLine(s);
}
static void Main()
{
PropertyEventsSample p = new PropertyEventsSample();
p.Event1 += new Delegate1(TestClass.Delegate1Method);
p.Event1 += new Delegate1(TestClass.Delegate1Method);
p.Event1 -= new Delegate1(TestClass.Delegate1Method);
p.FireEvent1(2);
p.Event2 += new Delegate2(TestClass.Delegate2Method);
p.Event2 += new Delegate2(TestClass.Delegate2Method);
p.Event2 -= new Delegate2(TestClass.Delegate2Method);
p.FireEvent2("TestString");
}
}
|
输出
请参见