如何使用引用委託實例而不是類實例的this
(或其他類型的東西)?使用引用匿名代理的「this」
instance.OnEventFoo += delegate()
{
if (condition)
{
instance.OnEventBar += this;
}
};
如何使用引用委託實例而不是類實例的this
(或其他類型的東西)?使用引用匿名代理的「this」
instance.OnEventFoo += delegate()
{
if (condition)
{
instance.OnEventBar += this;
}
};
既然你不能引用它宣告前一個變量,你必須:
// 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;
您需要將其存儲在一個變量的地方。例如:
EventHandler rowChanged = null; // to avoid "uninitialized variable" error
rowChanged = (s, e) =>
{
if (condition)
{
// this will unsubscribe from the event as expected
RowChanged -= rowChanged;
}
};
'RowChanged'事件是否通過inn'sender,e'? –
http://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp – Vadim
@ LasseV.Karlsen是的,但它沒有關係的例子:) – 56ka