开发者

Subscribe event in child class?

I thought I understand the events in C#. That sometimes they are used if you do not want to call the method directly rather than left place for custom implementation. But when?

Programmer A wri开发者_如何学编程tes class A, programmer B writes class B. Class A should raise an event that Class B register and reacts but Class A does not know anything about function that class B uses for serving.

Could you please provide me with simple example?


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);    
        }
    }
}


This is pretty basic and gets the point across.

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


When you say "they are used if you do not want to call the method directly rather than left place for custom implementation", you make me think that you may not completely understand the difference between a simple delegate and an event. Way oversimplifying here but here's a brief explanation...

Delegates are a way of letting someone who is writing code using your code to provide their own method. As such, they don't go through the message pump and occur synchronously etc.

Events use a delegate to provide a way for you to put your own code in to respond to the event. Events go through the message pump and are appropriate when there is something you need to respond to that may be happening elsewhere. However, they will occur outside of the execution path of the currently executing code.

Happily, most people seem to get when to use one or the other by instinct. Again, gross simplification here, but hopefully enough for further reading.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜