如何使用this
(或类似的东西)引用委托实例而不是类实例?
instance.OnEventFoo += delegate()
{
if (condition)
{
instance.OnEventBar += this;
}
};
答案 0 :(得分: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;
}
};