简体   繁体   English

有没有办法比较C#中_MSC_VER的值? 或者有另一种方法可以获取 C# 中的编译器版本吗?

[英]Is there a way to compare the value of _MSC_VER in C#? Or is there another way of getting the compiler version in C#?

I'd like to get the version of Visual Studio used to build a C# project without having to resort to C++/CLI.我想获得用于构建 C# 项目的 Visual Studio 版本,而不必求助于 C++/CLI。 When I use the following in C# the compiler complains.当我在 C# 中使用以下内容时,编译器会报错。

#if (_MSC_VER == 1500)
   // ... Do VC9/Visual Studio 2008 specific stuff
#elif (_MSC_VER == 1600)
   // ... Do VC10/Visual Studio 2010 specific stuff
#elif (_MSC_VER == 1700)
   // ... Do VC11/Visual Studio 2012 specific stuff
#endif

Is there a way to do this?有没有办法做到这一点? Thanks谢谢

One alternative would be to define symbols for conditional compilation within the project properties.一种替代方法是在项目属性中为条件编译定义符号。 For instance, you could add, DevEnv17 for VS2022 and DevEnv16 for VS2019.例如,您可以为 VS2022 添加 DevEnv17,为 VS2019 添加 DevEnv16。

Ensure you define the right symbols in project properties确保在项目属性中定义正确的符号

<Choose>
    <When Condition=" '$(VisualStudioVersion)' == '17.0' "> 
        <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Release|AnyCPU' ">
            <DefineConstants>DevEnv17</DefineConstants>
        </PropertyGroup>
    </When>
    <When Condition=" '$(VisualStudioVersion)' == '16.0' "> 
        <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Release|AnyCPU' ">
            <DefineConstants>DevEnv16</DefineConstants>
        </PropertyGroup>
    </When>
</Choose>

Then you could use C# preprocessor directives as below然后你可以使用 C# 预处理器指令如下

#if DevEnv17
    //Do VS2022 specific stuff
#elif DevEnv16
    //Do VS2019 specific stuff
#else
    //Do other VS IDE version stuff
#endif

Visual Studio 2022:视觉工作室 2022:

VS2022

Visual Studio 2019:视觉工作室 2019:

VS2019

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM