Sign event in child class?

I thought I understood the events in C #. Sometimes they are used if you do not want to name the method directly, and not the left place for a custom implementation. But when?

Programmer A writes class A, programmer B writes class B. Class A must fire an event that Class B detects and responds, but class A knows nothing about the function that class B uses to serve.

Could you provide me a simple example?

+3
source share
3 answers
public class A
{
    private readonly B _B = new B();

    public class A() 
    {
        _B.MyEvent += MyEventHandler; 
    }

    private void MyEventHandler(object sender, EventArgs e)
    {
        // Handle
    }
}

public class B
{
    public event EventHandler MyEvent;

    // Call this when you raise the event so you don't 
    // need check if MyEvent is null.
    private void OnMyEvent() 
    {
        if (MyEvent != null) // If this is null we have no subscribers.
        {
            MyEvent(this, EventArgs.Empty);    
        }
    }
}
+1
source

This is a fairly simple solution and makes sense.

http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

+1
source

: " , , ", , . , ...

- -, , , . , ..

, . , -, , . .

Fortunately, for most people it seems that they need to use this or that instinct. Again, a rough simplification here, but hopefully enough for further reading.

0
source

Source: https://habr.com/ru/post/1732570/


All Articles