首页 > 解决方案 > C# Preprocesors 指令与(c# 版本)

问题描述

预处理器有没有办法根据 C# 的版本执行代码?例子:

#if CSharpVersion = 7.3
var value = 1;
#endif

标签: c#visual-studio

解决方案


One option would be to define the LangVersion explicitly in the Project file and have the constants defined based on it. For example,

<LangVersion>7.3</LangVersion>

and

<DefineConstants Condition="'$(LangVersion)' == '7.3'">DEBUG;TRACE;LANG_VERSION_7_3</DefineConstants>
<DefineConstants Condition="'$(LangVersion)' != '7.3'">DEBUG;TRACE;LANG_VERSION_NOT_7_3</DefineConstants>

Now you could use directives as

#if LANG_VERSION_7_3
            Console.WriteLine("C# 7_3");
#elif LANG_VERSION_NOT_7_3
            Console.WriteLine("Not C# 7_3");
#endif 

Please note the LANG_VERSION would signify the compiler accepts syntax specified version or lower.


推荐阅读