本文介绍了自动创建空的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");
}

编辑:我从这篇文章得到了)

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

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

09-03 13:51