2013-12-16 37 views
3

如何使用引用委託實例而不是類實例的this(或其他類型的東西)?使用引用匿名代理的「this」

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

'RowChanged'事件是否通過inn'sender,e'? –

+1

http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp – Vadim

+0

@ LasseV.Karlsen是的,但它沒有關係的例子:) – 56ka

回答

4

既然你不能引用它宣告前一個變量,你必須:

  1. 首先聲明變量,
  2. 然後指定一個代表,
  3. 再註冊事件處理程序。

// 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; 
3

您需要將其存儲在一個變量的地方。例如:

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

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

他們有沒有辦法避免使用新的var? – 56ka

+0

@ 56ka不需要。您需要一個引用自身的委託。由於在聲明變量之前不能引用變量,因此需要先聲明變量。 – dcastro

+0

@ 56ka:不,但爲什麼會打擾你呢? – Jon