在VS2015中使用.net 4.5,但我被允许使用c# 6的特性

本文关键字:许使用 VS2015 net | 更新日期: 2023-09-27 18:05:35

我正在VS2015中工作,该项目针对。net框架4.5

在构建设置中,语言版本被设置为'default'

正如我所读到的,c# 6只在。net 4.6中添加,但我AM允许(至少,代码编译和运行)使用string interpolation功能,这是c# 6的一个功能。

现在我很困惑:我现在是在编译c# 6/。net 4.6还是。net 4.5(我怎么能检查呢?)

<标题>编辑

在评论中,我看到c# 6的语法与。net框架版本没有任何关系。我从这个答案(c#的正确版本号是什么?)中得到了这个想法,其中说"c# 6.0与。net 4.6和VS2015(2015年7月)一起发布。"所以我明白c# 6(以某种方式)耦合到。net 4.6

在VS2015中使用.net 4.5,但我被允许使用c# 6的特性

c# 6的特性,如字符串插值是编译器的特性,而不是运行时(CLR)的特性。因此,只要你的编译器支持c# 6,无论你是基于哪个版本的。net构建,都可以使用它们。

在Visual Studio 2015中,您可以在Properties => Build tab => Advanced button => Language Version

中控制您所针对的语言版本。

通常,c#编译器的新版本与。net框架的新版本同时发布。但是c#编译器并不依赖于你正在使用的框架的版本,而是依赖于特定的类型和成员。这些类型包含在新框架中,但它们也可以来自其他地方。

例如,这就是为什么你可以在。net 4.0上使用c# 5.0 async - await,使用Microsoft.Bcl.Async包。

特别对于c# 6.0,基本的字符串插值不需要任何新的类型或成员,所以它不需要新的框架版本。这段代码:

string s = $"pie is {3.14}";
Console.WriteLine(s);

编译:

string s = string.Format("pie is {0}", 3.14);
Console.WriteLine(s);

在。net 4.5上运行良好。

另一方面,字符串插值的一个高级特性是插入的字符串可以转换为IFormattableFormattableString。例如,下面的代码:

IFormattable formattable = $"pie is {3.14}";
Console.WriteLine(formattable.ToString(null, CultureInfo.InvariantCulture));
Console.WriteLine(formattable.ToString(null, new CultureInfo("cs-CZ")));

编译:

IFormattable formattable = FormattableStringFactory.Create("pie is {0}", 3.14);
Console.WriteLine(formattable.ToString(null, CultureInfo.InvariantCulture));
Console.WriteLine(formattable.ToString(null, new CultureInfo("cs-CZ")));

在。net 4.6上可以很好地编译,但在。net 4.5上使用

会失败。

错误CS0518:预定义类型"System.Runtime.CompilerServices"。没有定义或导入FormattableStringFactory

但是您可以通过包含以下代码使其编译:

namespace System.Runtime.CompilerServices
{
    class FormattableStringFactory
    {
        public static IFormattable Create(string format, params object[] args) => null;
    }
}

当然,对于这个虚拟实现,下面的代码将抛出一个NullReferenceException

您实际上可以通过引用非官方的StringInterpolationBridge包来使它工作。