Partager via


How to: Use a Dictionary to Store Event Instances (C# Programming Guide) 

One use for accessor-declarations is to expose a large number of events without allocating a field for each event, but instead using a Dictionary to store the event instances. This is only useful if you have a very large number of events, but you expect most of the events will not be implemented.

Example

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");
    }
}

Output

2
TestString

See Also

Concepts

C# Programming Guide
Events (C# Programming Guide)
Delegates (C# Programming Guide)