自动创建空的C#事件处理程序 [英] Create empty C# event handlers automatically

查看:85
本文介绍了自动创建空的C#事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是不可能的火在不具有连接到它的处理程序的C#的事件。所以每次打电话之前,有必要检查事件为null。

It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.

if ( MyEvent != null ) {
  MyEvent( param1, param2 );
}

我想保持我的code尽可能干净,摆脱那些null检查。我不认为它会在我的情况会影响性能非常多,至少没有。

I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case.

MyEvent( param1, param2 );

现在,我通过手动添加一个空行内处理每个事件解决这个问题。这是很容易出错的,因为我需要记住这样做等。

Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc.

void Initialize() {
  MyEvent += new MyEvent( (p1,p2) => { } );
}

有没有产生一个给定类的所有事件处理程序空的方式自动使用反射和一​​些CLR的魔力?

Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?

推荐答案

我看到这个的另一职务,并无耻地窃取,并用它在我的很多code的自从:

I saw this on another post and have shamelessly stolen it and used it in much of my code ever since:

public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate {}; // add empty delegate!

//Let you do this:
public void DoSomething() {
    Click(this, "foo");
}

//Instead of this:
public void DoSomething() {
    if (Click != null) // Unnecessary!
        Click(this, "foo");
}

<击> *如果有人知道这个技术的起源,请张贴在评论中。我真的相信在源获取,由于信贷。

编辑:我从这篇文章得到它隐藏的特征C#?

这篇关于自动创建空的C#事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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