没有静态的单个对象实例 [英] Single Object Instance without static

查看:68
本文介绍了没有静态的单个对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我很懒,但只是为了检查是否有更好的想法。

我在用户控件中有一个事件

Hi I know i am lazy but just to check if there is any better ideas around.
I had an event in a usercontrol

public event EventHandler EH_OpenDefaultClick;





单击单选按钮时的表单将订阅此事件。但是这个表单不会被销毁,只要单击单选按钮,我就会订阅该事件



A form when a radio button is click will subscribe to this event. However this form will not be destroyed and whenever the radio button is click, i will subscribe to the event

ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;





只有上面的唯一一行,每次订阅,因此触发多次。我可以添加代码来比较它是否为null。但最终代码对所有这些都不整齐== null





with the only line above, every time it will be subscribe, hence triggering multiple time. I can add in the code to compare if it is null. But eventually codes get untidy with all these == null

if (ucStdButton_Recipe.EH_OpenDefaultClick == null)
    ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;





我无法将事件声明为静态,因为事件是在运行时订阅的。是否有任何声明类型允许我在没有比较语句的情况下更容易订阅



I cannot declare the event as static as the event is subscribe during runtime. Is there any declaration type allowing me to subscribe more easily without the comparison statement

推荐答案

您可以检查特定的处理程序订阅:



You can check for a specific handler subscription:

public bool IsHandlerSubbed(Delegate handler)
{   
	if ( this.EventHandler != null )
	{
		foreach ( Delegate h in this.EventHandler.GetInvocationList() )
		{
			if ( h == handler)
			{
				return true;
			}
		}
	}
	return false;
}


您可以在添加之前通过取消订阅来阻止它:

You can prevent it by unsubscribing before adding it:
ucStdButton_Recipe.EH_OpenDefaultClick -= ucStdButton_Recipe_EH_OpenDefaultClick;
ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;


这篇关于没有静态的单个对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆