且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何摆脱“ [某些事件]从未使用过”的问题, Visual Studio中的编译器警告?

更新时间:2022-12-14 17:19:55

这似乎是警告67 ,因此可以通过以下方式禁止显示:

This appears to be warning 67 and can thus be suppressed with:

#pragma warning disable 67

别忘了将其还原为

#pragma warning restore 67






但是,我会再次检查并确保您正在加薪某个地方的事件,而不是只是订阅。当您注释掉事件时,编译器会发出20个警告而不是20个错误的事实也令人怀疑...


However, I'd check again and make sure you're raising the event somewhere, not just subscribing to it. The fact that the compiler spits out 20 warnings and not 20 errors when you comment out the event is also suspicious...

还有关于此警告的有趣文章,特别是它如何应用于界面;关于如何处理未使用事件,有很好的建议。重要的部分是:

There's also an interesting article about this warning and specifically how it applies to interfaces; there's a good suggestion on how to deal with "unused" events. The important parts are:


正确的答案是明确说明您希望从事件中得到什么,在这种情况下,答案是什么:

The right answer is to be explicit about what you expect from the event, which in this case, is nothing:

public event EventHandler Unimportant
{
    add { }
    remove { }
}

这将完全消除警告,以及正常情况下由编译器生成的额外实现事件。另外一个好处是,它促使人们思考这种无所事事的实现是否真的是***的实现。例如,如果事件不是很重要而不是不受支持的,那么如果没有该事件,依赖该功能的客户端很可能会失败,那么***通过抛出一个错误来明确表示缺乏支持并快速失败。例外:

This will cleanly suppress the warning, as well as the extra compiler-generated implementation of a normal event. And as another added benefit, it prompts one to think about whether this do-nothing implementation is really the best implementation. For instance, if the event isn't so much unimportant as it is unsupported, such that clients that do rely on the functionality are likely to fail without it, it might be better to explicitly indicate the lack of support and fail fast by throwing an exception:

public event EventHandler Unsupported
{
    add { throw new NotSupportedException(); }
    remove { }
}

当然,可以在没有部分功能的情况下进行有效地实现,有时表明该接口不是***内聚的,应将其拆分为单独的接口。

Of course, an interface that can be usefully implemented without some parts of its functionality is sometimes an indication that the interface is not optimally cohesive and should be split into separate interfaces.