【问题标题】:Visual Studio suggests C# 8.0 features, but compiler yields errorVisual Studio 建议使用 C# 8.0 功能,但编译器会产生错误
【发布时间】:2019-10-04 08:23:38
【问题描述】:

在我的项目中,Visual Studio 建议我将 C# 8.0 功能用于 Framework 4.6 项目,即使 Microsoft 文档中将默认值指定为 7.3。建议之一的示例:

var i1 = "";
var i2 = "";
i1 = i1 ?? i2; //suggests i1 ??= i2;

如果我让 VS 更正建议,IDE 不会向我显示任何错误或警告,但在我构建的那一刻,我会收到编译器错误。

我知道我可以更改 .csproj 文件中的 langversion 以使其正常工作,但这不是重点。

为什么我得到建议,然后在编译之前没有错误?

在我的记忆中,如果我想使用该版本的功能,我过去曾收到建议,将项目自动升级到 langversion 以获得 7.X 功能。

.csproj 文件之一的示例:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{00000000-0000-0000-0000-000000000000}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>MyProject</RootNamespace>
    <AssemblyName>MyProject</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  //... References & compilation files
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

【问题讨论】:

  • 向我们展示您的项目文件 (*.csproj) 的 xml
  • 奇怪的是,C# 8 不支持 .NET 4.6(也包括 4.7 和 4.8),因为它需要 .NET Standard 2.1 的东西才能工作。更多 here 在“平台依赖”下
  • 我的 VS 没有这样的建议,你确定不是扩展?尝试在安全模式下启动 CS(从命令行devenv.exe -SafeMode),看看它是否仍然发生。
  • 根据this more differentiated answer,可以在项目文件中手动设置语言版本,并使用旧框架中的一些C#8.0特性。可以使用纯语法的东西。不能使用需要在运行时更改的默认接口方法。不能使用框架中需要新类型的索引和范围以及异步流。

标签: visual-studio-2019 .net-4.6 c#-8.0


【解决方案1】:

更新 Microsoft.Net.Compilers NuGet 包对我有用。

我从 2.10.0 更新到 3.11.0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多