I tried to unsubscribe from a lambda within itself. I used the MethodInfo class for getting information about a lambda and the Delegate.CreateDelegate method for creating the same method as a lambda. So it works fine if a lambda created in one of the class methods that contains the event i use but doesn't work in another class method (binding exception).
Here's the code:
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
}
}