如何摆脱“ [某些事件]从未使用过”的问题, Visual Studio中的编译器警告? [英] How do I get rid of "[some event] never used" compiler warnings in Visual Studio?

查看:88
本文介绍了如何摆脱“ [某些事件]从未使用过”的问题, Visual Studio中的编译器警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我收到此编译器警告

For example, I get this compiler warning,


从未使用事件'Company.SomeControl.SearchClick'。

The event 'Company.SomeControl.SearchClick' is never used.

但是我知道它已被使用,因为注释掉它会使我像尝试使用此事件的XAML页面的20条新警告!

But I know that it's used because commenting it out throws me like 20 new warnings of XAML pages that are trying to use this event!

有什么用?有没有技巧可以消除此警告?

What gives? Is there a trick to get rid of this warning?

推荐答案

这似乎是警告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.

这篇关于如何摆脱“ [某些事件]从未使用过”的问题, Visual Studio中的编译器警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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