Visual Studio忽略#if DEBUG / RELEASE范围内的代码,不检查错误或自动完成

问题描述 投票:6回答:3

我一直在写一个#if DEBUG#else#endif代码片段,我注意到Visual Studio不允许我使用自动完成来实现部分类型的成员名称,并且它不会检查灰色的非活动代码是否有错误。我发现再次关注的唯一方法是将构建模式从Debug切换到Release。但这很不方便,感觉有更好的方法。

例:

#if DEBUG
    throw;
#else
    throw new exc // I want to use autocomplete here but can't because it's greyed out
#endif

如何让VS停止忽略#if DEBUG的其他配置范围内的其他代码?

c# visual-studio-2017 preprocessor-directive
3个回答
7
投票

它是条件编译的目的,它按预期工作。使用条件编译应用程序可以在编译时忽略某些代码。您在Visual Studio中的应用程序正在调试模式下运行,因此编译器忽略#elsepart中的代码。

在发布模式下运行您的应用程序,然后#else代码将可用,但#if DEBUG将不可用。

enter image description here

更新


要检查#if DEBUG#else,您需要运行两次应用程序。

1.在调试模式下,使用#if DEBUG的代码如下:

enter image description here enter image description here

这里的应用程序处于调试模式,所以#if DEBUG条件代码是活动的..

  1. 在发布模式下运行应用程序以检查#else条件中的代码。其他部分也可以使用自动完成和调试。

enter image description here enter image description here


有关详细信息,请参阅microsoft docs:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/debug-compiler-option

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-by-category


3
投票

我知道这是一个迟到的答案,但它仍然适用于今天。

TL; DR:this is a VS bug,其影响仅影响netstandard / netcore项目(或简称为新的.csproj格式)。

解决方法是......讨厌! Reload the project file(或关闭并重新开启VS)。

好消息:这不影响编译:)

你可以阅读更多herehere


0
投票

在文件的开头定义两个常量:

#define DEBUG
#define RELEASE

接下来,使用两个if条件而不是if/else

#if DEBUG
            // autocomplete works
#endif
#if RELEASE
            // autocomplete works
#endif

当然,您必须在编译项目之前删除/注释掉这些定义。

在我看来,这种尴尬和充满错误。

© www.soinside.com 2019 - 2024. All rights reserved.