使用“this”引用匿名代表

时间:2013-12-16 09:32:49

标签: c# delegates

如何使用this(或类似的东西)引用委托实例而不是类实例?

instance.OnEventFoo += delegate()
    {
        if (condition)
        {
            instance.OnEventBar += this;
        }
    };

2 个答案:

答案 0 :(得分:4)

由于在声明变量之前无法引用变量,因此必须:

  1. 首先声明变量
  2. 然后分配一名代表,
  3. 然后使用事件注册处理程序。

  4. // Add an anonymous delegate to the events list and auto-removes automatically if item disposed
    DataRowChangeEventHandler handler = null;
    handler = (sender, args) =>
        {
            if (condition)
            {
                // need to remove this delegate instance of the events list
                RowChanged -= handler;
            }
        };
    
    something.RowChanged += handler;
    

答案 1 :(得分:3)

您需要将其存储在某个变量中。例如:

EventHandler rowChanged = null; // to avoid "uninitialized variable" error

rowChanged = (s, e) =>
{
    if (condition)
    {
        // this will unsubscribe from the event as expected
        RowChanged -= rowChanged;
    }
};