Answer the question
In order to leave comments, you need to log in
Recalling events?
Hello everyone, I have this example:
public delegate void EventDelegate();
public class MyClass
{
public event EventDelegate myEvent = null;
public void InvokeEvent()
{
myEvent.Invoke();
}
}
class Program
{
// Методы обработчики события.
static private void Handler1()
{
Console.WriteLine("Обработчик события 1");
}
static private void Handler2()
{
Console.WriteLine("Обработчик события 2");
}
static void Main()
{
MyClass instance = new MyClass();
// Присоединение обработчиков событий. (Подписка на событие)
instance.myEvent += new EventDelegate(Handler1);
instance.myEvent += Handler2;
// Метод который вызывает событие.
instance.InvokeEvent();
Console.WriteLine(new string('-', 20));
// Открепляем Handler2().
instance.myEvent -= new EventDelegate(Handler2);
instance.InvokeEvent();
// Delay.
Console.ReadKey();
}
}
Answer the question
In order to leave comments, you need to log in
Because an event is not the same as a delegate. The event limits the delegate interface to only two operations - add and remove a handler. This is done so that only from inside the object can an event be generated. In other words, so that no one could, for example, "click" the button instead of the button itself (ie, generate the Clicked event, bypassing the internal logic of the "Button" class). This is the fundamental meaning of the concept of events.
An analogy can be drawn between a field/property and a delegate/event. As a property, it is in some cases an "interface" for a field that allows you to control how it changes (in this case, you can use the generated field using the syntax{ get; set; }
), so an event is an "interface" to a delegate - you can't directly change or call a delegate, you do it with an event. You can also read about the add / remove syntax for events - then the analogy with the property will be even clearer.
Why do InvokeEvent is not entirely clear, apparently this is just some kind of example. In real code, the MyClass class must decide for itself when to raise a particular event.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question