简体   繁体   English

如何声明事件为强制性

[英]How to declare an event mandatory

I have a user control that has a contextmenustrip that is displayed on every right click. 我有一个用户控件,该控件具有一个右键单击时显示的contextmenustrip。 When the user select an item on this menu, I have to pass this info to the parent control so it can react according to this. 当用户在此菜单上选择一个项目时,我必须将此信息传递给父控件,以便它可以对此做出反应。

So I need the parent to mandatory subscribe to this event. 因此,我需要父母强​​制订阅此事件。 Is there a way to tell that? 有办法告诉我吗?

If there is no way to do that, should I throw an exception or just check for null value (of the event handler) and do nothing? 如果没有办法做到这一点,我应该抛出异常还是仅检查(事件处理程序的)空值,什么都不做?

Thanks. 谢谢。

There is no way to enforce this at compile time - meaning that there is nothing in the .NET framework/C# language that can perform static checks at compilation to ensure that this logic is implemented in your code. 无法在编译时强制执行此操作-意味着.NET Framework / C#语言中没有任何东西可以在编译时执行静态检查,以确保在您的代码中实现此逻辑。

At run-time you can perform the necessary validation. 在运行时,您可以执行必要的验证。 For instance you might inspect the invocation list of the delegate to ensure that the parent is in that list. 例如,您可以检查委托的调用列表以确保父代在该列表中。

You can create a specific constructor for your user control to prevent instantiation unless an event handler is given, like this. 您可以为用户控件创建一个特定的构造函数,以防止实例化,除非这样指定了事件处理程序。

public partial class MyUserControl : UserControl {
    public MyUserControl (ToolStripItemClickedEventHandler handler) {
        InitializeComponent ();
        myContextMenuStrip.ItemClicked += handler;
    }
}

Do note though: this won't work very well with Visual Studio's form designer, as the form designer generally expects parameter-less constructors. 不过请注意:这与Visual Studio的表单设计器配合不太好,因为表单设计器通常期望使用无参数的构造函数。 Instead, you need to manually create the control instance from code. 相反,您需要根据代码手动创建控件实例。

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

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