简体   繁体   中英

How to raise an event when a new handler is assigned?

I am trying to copy functionality provided by an existing .NET XNA class's event: NetworkSession.GamerJoined .

When the event is assigned to it can immediately be raised, eg:

myNetworkSession.GamerJoined += GamerJoinedEventHandler;

void GamerJoinedEventHandler(object sender, GamerJoinedEventArgs e)
{
    // If you put a beakpoint on the assignment line above and another here
    // this handler is called during the assignment.
}

How can I achieve this if I am writing my own NetworkSession class with the GamerJoined event?

Yes, you can do this using the add contextual keyword.

When you have the line:

public event EventHandler<GamerJoinedEventArgs> GamerJoined;

This is syntactic sugar for:

public event EventHandler<GamerJoinedEventArgs> GamerJoined
{
    add
    {
        this.gamerJoined += (EventHandler<GamerJoinedEventArgs>)Delegate.Combine(this.gamerJoined, value);
    }
    remove
    {
        this.gamerJoined -= (EventHandler<GamerJoinedEventArgs>)Delegate.Remove(this.gamerJoined, value);
    }
}

Where gamerJoined is a private backing field for the event. So you can write you own add to call the handler eg

public event EventHandler<GamerJoinedEventArgs> GamerJoined
{
    add
    {
        this.gamerJoined += (EventHandler<GamerJoinedEventArgs>)Delegate.Combine(this.gamerJoined, value);
        value(this, new GamerJoinedEventArgs(myGamer));
    }
    remove
    {
        this.gamerJoined -= (EventHandler<GamerJoinedEventArgs>)Delegate.Remove(this.gamerJoined, value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM