C#:是否需要恢复编译指示警告?
从 msdn 我得到这个:
#pragma warning disable warning-list
#pragma warning restore warning-list
在示例中,同时使用disable
和restore
。 如果我希望对整个文件禁用它,是否有必要恢复
?
比如,如果我不恢复,它能走多远? 之后编译的所有内容都会禁用警告吗? 或者只是该文件的其余部分? 还是被忽略了?
From msdn I get this:
#pragma warning disable warning-list
#pragma warning restore warning-list
In the examples, both disable
and restore
are used. Is it necessary to restore
if I want it disabled for a whole file?
Like, if I do not restore, how far does it carry? Are the warnings disabled for everything compiled after that? Or just for the rest of that file? Or is it ignored?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不恢复,则文件的其余部分将处于禁用状态。
有趣的是,这种行为语言规范。
(参见第 9.5.8 节)然而,关于条件编译符号的 9.5.1 节确实表明了这一点“直到文件行为结束”
鉴于“预处理器”实际上是编译的词法分析阶段的一部分,这种行为很可能是微软和可预见的未来所有其他实现的有效契约(特别是因为替代方案将非常复杂且基于非确定性)关于源文件编译顺序)
If you do not restore the disabling is active for the remainder of the file.
Interestingly this behaviour is not defined in the language specification.
(see section 9.5.8) However the 9.5.1 section on Conditional compilation symbols does indicate this "until end of file behaviour"
Given the 'pre-processor' is actually part of the lexical analysis phase of compilation it is likely that this behaviour is an effective contract for Microsoft's and all other implementations for the foreseeable future (especially since the alternate would be hugely complex and non deterministic based on source file compilation order)
假设我有一个使用反射初始化的私有字段,编译器显然找不到任何直接写入该字段的代码,因此它将显示一个警告 - 我不想显示。
还假设我在第一行下面定义了另一个私有字段,但我忘记初始化该字段,如果我禁用整个文件的警告,则不会触发警告。
因此,#pragma warning 的最佳用法是在导致我想要抑制的警告的行之前放置一个“警告禁用”,并在该行之后放置一个“警告恢复”,以便在不同位置中的相同条件文件仍然会触发警告。
Let's say I have a private field that is initialized using reflections, the compiler obviously can't find any code directly writing into this field so it will show a warning - that I don't want to show.
Let's also say I have another private field defined 3 lines below the first that I forgot to initialize, if I disable the warning for the entire file this will not trigger a warning.
So, the best usage for #pragma warning is to put a "warning disable" right before the line that causes the warning that I want to suppress and a "warning restore" right after the line so the same condition in a different location in the file will still trigger a warning.
不,您会发现编译器完成解析源文件后会自动恢复任何禁用的警告。
在上面的示例中,我已关闭警告 CS00649,因为我打算以不安全的方式使用此结构。 编译器不会意识到我将写入具有这种布局的内存,因此我想忽略警告:
但我不希望整个文件不被选中。
No, you'll find that the compiler will automatically restore any disabled warning once it's finished parsing a source file.
In the above example I've turned of warning CS00649 because I intend to use this struct in an unsafe manner. The compiler will not realize that I will be writing to memory that has this kind of layout so I'll want to ignore the warning:
But I don't want the entire file to not be left unchecked.