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

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

问题描述

无法在 C# 中触发没有附加处理程序的事件.所以每次调用前都要检查事件是否为空.

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 );
}

我想尽可能保持我的代码干净并摆脱那些空检查.我认为它不会对性能产生太大影响,至少在我的情况下不会.

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?

推荐答案

我在另一个帖子上看到了这个,并且无耻地偷了它并在我的大部分代码中使用它:

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#?)

( I got it from this post Hidden Features of C#?)

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

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