Hello everyone, I am passing a course on c #

there is a line:

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

as noted by the author of the course - It is impossible to detach the 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 doesn’t the above method of lambda method detaching work?

2) How to detach the lambda method?

3) If the lambda method is not so easily detached, can I (I don’t remember exactly if the lambda method takes the parameters into the constructor) pass a call to its constructor, for example, some other usual method, for example, the malicious method we created is a dirty trick) which will be called on this event - via the lambda method - caused by this event? For example, in case of an event - "clicking with a mouse" (written by us and not ready (standard) if such is available) - through a lambda method to call some kind of "malicious method"

  • 2
    It seems to me, it is not necessary to engage in video tutorials. Nothing is better than books. - VladD 4:34 pm

1 answer 1

  1. You must, when unsubscribing, specify the same handler as when subscribing. If you write

     instance.MyEvent += delegate { Console.WriteLine("Анонимный метод 1."); }; instance.MyEvent -= delegate { Console.WriteLine("Анонимный метод 1."); }; 

    - then the second line you try to unsubscribe a new delegate that does not coincide with the delegate from the first line (each construction of the type delegate { ... } creates a new delegate). So unsubscribe will not work.

  2. Detach is very simple. Write your handler to a variable:

     EventDelegate handler = delegate { Console.WriteLine("Анонимный метод 1."); }; instance.MyEvent += handler; ... instance.MyEvent -= handler; 

    If necessary, memorize the handler in the field of your class.

  3. Yes of course. Inside the delegate-subscriber there can be any code as maliciously as you like. As a programmer, you are responsible for knowing which code is malicious and which is not, and not run the malicious code. (Or run, if you so want.)


By the way, the record in the form of delegate { ... } is a very ancient syntax. Now nobody writes like that, but they use lambda notation: () => Console.WriteLine("Анонимный метод 1.") .