B
B
BadCats2016-08-03 19:09:52
C++ / C#
BadCats, 2016-08-03 19:09:52

Detach lambda method from event?

Hello everyone, I'm taking a course on c #
there is a line:

// Невозможно открепить ранее присоединенный анонимный метод.
            instance.MyEvent -= delegate { Console.WriteLine("Анонимный метод 1."); };

as noted by the author of the course - It is not possible to detach a previously attached anonymous method
, but, after a while, an amendment is made to the fact that an anonymous method acting as an event handler is still possible to detach, but "... you will see this detachment technique in the next course" .
The question arises:
1) why does the above method of detaching the lambda method not work?
2) how to detach the lambda method?
3) If detaching the lambda method is not so easy, then is it possible (I don’t remember exactly whether the lambda method takes parameters in the constructor) to its constructor pass a call, for example, to some other usual one, for example, the "malicious" method we created (which will do some -something dirty trick) that will be called on this event - via the lambda method - called by this event? For example, at the event - "clicking the mouse" (written by us and not ready (standard) if any) - call some "malicious method" through the lambda method.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
MrDywar Pichugin, 2016-08-03
@Dywar

stackoverflow.com/questions/183367/unsubscribe-ano...

Action myDelegate = delegate(){Console.WriteLine("I did it!");};

MyEvent += myDelegate;


// .... later

MyEvent -= myDelegate;

But listen to this guy:
"From memory, the specification explicitly doesn't guarantee the behavior either way when it comes to equivalence of delegates created with anonymous methods.
If you need to unsubscribe, you should either use a "normal" method or retain the delegate somewhere else so you can unsubscribe with exactly the same delegate you used to subscribe."
Jon Skeet

Михаил, 2016-08-04
@Madfisht3

Для события только += или -=; Это для того и делается, чтобы защитить от шаловливых рук, чтобы не смогли извлечь из события и запускать вручную то, что привязано к событию.
И еще:

Action m1 = delegate { Console.WriteLine("Анонимный метод 1."); };
Action m2 = delegate { Console.WriteLine("Анонимный метод 1."); };
 m1 == m2 //False

Я знаю два варианта, слабые ссылки или хранение и отписка.

Роман, 2016-08-07
@yarosroman Куратор тега C#

От анонимного метода или лямбды нельзя отписаться!!!!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question