简体   繁体   English

将事件添加到控件库的正确方法

[英]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. 我正在编写Winforms控件,该控件包装了JS库并扩展了Web浏览器控件。

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. 当JS库调用一个事件时,我有一个C#中的方法的回调,该方法解析返回的JSON等。在该方法的结尾,我想使用从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 . 如果用户尚未将自己的处理程序添加到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)? 我是否应该在类的构造函数中向事件添加处理程序,以使其永远不会为null(对象将捕获其自己的事件)? 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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