简体   繁体   中英

Proper way to add event to control library

I'm writing a Winforms Control, that wraps a JS library and extends a web browser control.

When the JS library, calls an event, I have a callback to a method in C# that parses the returned JSON etc... At the end of that method, I want to fire an event, with the data returned from JS.

I'm doing the following:

public event EventHandler<WebMercatorCoordinates> OnMapClick;
public void JavascriptCallbackReceiver(String message)
        {
           //I'm parsing the string here
           if (OnMapClick != null)
                this.OnMapClick(this, new WebMercatorCoordinates(lat, lng));
        }

I do not like that null check. I have to check for it, so as to not call a null delegate, if the user has not added his own handler to EventHandler<WebMercatorCoordinates> OnMapClick .

Should I, in the constructor of the class, add a handler to the event so that it is never null (the object will catch its own event)? I don't like that either (sounds way worse).

Is there some better way to design/wirte this?

使用C#6 空条件运算符,您可以编写:

OnMapClick?.Invoke(this, new WebMercatorCoordinates(lat, lng));

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