c# - 如何摆脱 Visual Studio 中的 "[some event] never used"编译器警告?

标签 c# .net wpf events compiler-warnings

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

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

但我知道它已被使用,因为将其注释掉会引发 20 个试图使用此事件的 XAML 页面的新警告!

什么给了?是否有摆脱此警告的技巧?

最佳答案

这似乎是 warning 67因此可以被抑制:

#pragma warning disable 67

不要忘记尽快(在事件声明之后)恢复它:

#pragma warning restore 67

但是,我会再次检查并确保您在某处提出事件,而不是只是订阅。当您注释掉该事件时,编译器发出 20 个警告 而不是 20 个错误 这一事实也很可疑...

还有 an interesting article关于这个警告,特别是它如何应用于接口(interface);关于如何处理“未使用”事件有一个很好的建议。重要的部分是:

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.

关于c# - 如何摆脱 Visual Studio 中的 "[some event] never used"编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1093315/

相关文章:

c# - 环绕面板 : Trying to make the ItemWidth equal to the max width of any one element

c# - 在 XAML 属性声明中绑定(bind)到父级?

c# - Button Click to get an Object on SelectionChanged 事件

c# - Uri规范化压缩FTP方案

.net - 当字符串 > 751 个字符时为 "Length of the data to decrypt is invalid"

c++ - 如何在 C++ VS2012 中转换或创建 .NET v3.5 解决方案(特别是工具集)

c# - WPF Datagrid 不显示所有值

c# - 在 C# 中从数据库加载组合框

c# - edititemtemplate gridview asp.net 中的下拉列表

.net - 适用于 .NET 的 SAML 库/组件