Unsubscribe anonymous method in C#

前端 未结 11 1242
夕颜
夕颜 2020-11-22 05:16

Is it possible to unsubscribe an anonymous method from an event?

If I subscribe to an event like this:

void MyMethod()
{
    Console.WriteLine(\"I di         


        
11条回答
  •  难免孤独
    2020-11-22 05:49

    If the best way is to keep a reference on the subscribed eventHandler, this can be achieved using a Dictionary.

    In this example, I have to use a anonymous method to include the mergeColumn parameter for a set of DataGridViews.

    Using the MergeColumn method with the enable parameter set to true enables the event while using it with false disables it.

    static Dictionary subscriptions = new Dictionary();
    
    public static void MergeColumns(this DataGridView dg, bool enable, params ColumnGroup[] mergedColumns) {
    
        if(enable) {
            subscriptions[dg] = (s, e) => Dg_Paint(s, e, mergedColumns);
            dg.Paint += subscriptions[dg];
        }
        else {
            if(subscriptions.ContainsKey(dg)) {
                dg.Paint -= subscriptions[dg];
                subscriptions.Remove(dg);
            }
        }
    }
    

提交回复
热议问题