C#:有什么方法可以抑制类似于抑制警告消息的编译器错误? [英] C#: Any way to suppress compiler errors similar to suppressing warning messages?

查看:30
本文介绍了C#:有什么方法可以抑制类似于抑制警告消息的编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下生成编译器错误的代码:

I have the following code that generates a compiler error:

    Boolean IConvertible.ToBoolean(IFormatProvider provider)
    {
        ThrowHelper.ThrowInvalidCast(typeof(MyType), typeof(Boolean));
    }

编译器抱怨不是所有的代码路径都返回一个值.这里的问题是 ThrowHelper 会总是抛出一个错误.它是一个调用静态方法的静态类.

The compiler is complaining that not all code paths return a value. The problem here is that ThrowHelper will ALWAYS throw an error. It is a static class calling a static method.

我知道我可以在 ThrowHelper 调用之后用一个愚蠢的返回真"来满足编译器,但这似乎是不必要的代码.我知道我可以抑制警告消息,但是当我尝试使用 SuppressMessageAttribute 时,它并没有阻止编译器发出抱怨.有什么办法可以仅针对此方法抑制此错误?

I understand that I can satisfy the compiler with a silly "return true" after the ThrowHelper call, but that seems like unnecessary code. I know I can suppress warning messages, but when I tried to use the SuppressMessageAttribute it doesn't stop the compiler from complaining. Any way to suppress this error only for this method?

推荐答案

除了修复错误之外,没有其他方法可以抑制错误.

There is no way to suppress an error other than to fix it.

错误,就其性质而言,表明编译器认为它无法生成有效代码.抑制错误的唯一方法是修复它们.只需添加它想要的 return 语句,然后在 Microsoft Connect 上提出一个问题,表明你认为编译器弄错了.

An error, by its nature, is indicating that the compiler believes it cannot generate valid code. The only way to suppress errors is to fix them. Just add the return statement it wants and then raise an issue on Microsoft Connect indicating that you believe the compiler is getting this one wrong.

然而,我怀疑这是预期的行为,因为编译器不知道您正在调用的方法将始终抛出并且以可预测的方式确定任何可能的调用树将很难,如果不是不可能的话(想象一下如果在以 throw 结束之前调用了 20 个方法链).

I suspect, however, that this is expected behaviour as the compiler is not aware that the method you are calling will always throw and to determine that in a predictable manner for any possible call tree would be difficult, if not impossible (imagine if you called a chain of 20 methods before concluding with a throw).

这篇关于C#:有什么方法可以抑制类似于抑制警告消息的编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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