C# 7 .NET / CLR / Visual Studio 版本要求

C# 7 .NET / CLR / Visual Studio version requirements

运行 C# 7 的最低 .NET 框架和 CLR 版本要求是什么?另外,我需要 VS 2017 来编译 C# 7 吗?

您不需要以 .NET 4.6 及更高版本为目标,这是不正确的。要使用元组,您需要 System.ValueTuple NuGet 包。就在 https://www.nuget.org/packages/System.ValueTuple/ you can see it says it supports 4.5 and above, and actually, it supports 4.0 and above. And if you want to get crazy, if you create your own System.ValueTuple class that does exactly what that package does, it will work back on .NET 3.5 and probably older too. For "Task-like" types, you also need a NuGet package, https://www.nuget.org/packages/System.Threading.Tasks.Extensions/。根据其文档,此包也适用于 .NET 4.5 和更新版本。

其他 C# 7 功能仅适用于 .NET 2 及更高版本,因为它们只是语法糖。例如,我刚刚在 .NET 2.0 中编写了以下内容并且它正确地抛出:

static void Main(string[] args)
{
    string test = null;
    string d = test ?? throw new ApplicationException("test");
}

同样,int.TryParse("123", out int i); 在 .NET 2.0 中工作得很好。

我没有测试每一个 C#7 功能,但总的来说,除了元组(及其相关功能,如解构),它应该在 .NET 2.0 及更高版本中工作,因为其中大部分只是语法糖。也就是说,是的,你需要 VS2017 来编译 C#7。我敢肯定,在某些时候其他编译器会支持 C#7,但不是今天。

我确认在 .NET 2.0 中工作的功能:

  • 二进制文字
  • 数字分隔符
  • 内联out参数
  • 使用_丢弃参数
  • 局部函数
  • 基于类型的模式匹配 if (obj is int i)case int i:
  • 常量模式匹配if (i is 2)
  • Var 模式匹配 if (i is var j)
  • 参考 returns
  • 抛出表达式
  • 表达式主体 getter 和 setter
  • 表达式主体构造函数和终结器

要开箱即用地使用 C# 7 的全部功能(不引用 NuGet 包等),您需要 VS 2017 和 .NET 4.7 作为目标框架。