我試圖從其內部取消訂閱lambda。我使用MethodInfo類獲取有關lambda的信息,並使用Delegate.CreateDelegate方法創建與lambda相同的方法。因此,如果在包含我使用的事件的類方法之一中創建的lambda表達式工作正常,但在另一個類方法(綁定異常)中不起作用。針對事件和綁定異常的一次性lambda
下面的代碼:
public class TestClass
{
public event Action SomeEvent;
public void OnSomeEvent()
{
if (SomeEvent != null)
{
SomeEvent();
}
}
public TestClass()
{
//IT WORKS FINE!!!
//SomeEvent +=() =>
//{
// Console.WriteLine("OneShotLambda");
// MethodInfo methodInfo = MethodInfo.GetCurrentMethod() as MethodInfo;
// Action action = (Action)Delegate.CreateDelegate(typeof(Action), this, methodInfo);
// SomeEvent -= action;
//};
}
}
class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass();
t.SomeEvent +=() =>
{
Console.WriteLine("OneShotLambda");
MethodInfo methodInfo = MethodInfo.GetCurrentMethod() as MethodInfo;
//GOT AN ERROR
Action action = (Action)Delegate.CreateDelegate(typeof(Action), t, methodInfo);
t.SomeEvent -= action;
};
t.OnSomeEvent();
t.OnSomeEvent(); //MUST BE NO MESSAGE
}
}
http://stackoverflow.com/questions/5623658/single-shot-event-subscription – spender