在VS2015中定位.Net 4.5但我可以使用C#6功能吗?

时间:2016-09-05 08:12:01

标签: c# visual-studio-2015 c#-6.0

我正在VS2015中开展针对.Net framework 4.5的项目

在构建设置中,语言版本设置为“默认”

正如我所读到的,C#6仅在.Net 4.6中添加,但我 AM 允许(至少代码编译并运行)使用string interpolation功能,我读过的是C#6功能。

现在我很困惑:我现在正在编译C#6 / .Net 4.6或.Net 4.5(我怎么能检查它?)

修改

在评论中我看到C#6语法与.NET框架版本无关。 我从这个答案中得到了一个想法(What are the correct version numbers for C#?),其中说“使用.NET 4.6和VS2015(2015年7月)发布了C#6.0”。所以我理解C#6(以某种方式)与.NET 4.6耦合

2 个答案:

答案 0 :(得分:7)

C#6等字符串插值功能是编译器功能,而不是运行时(CLR)功能。因此,只要您的编译器支持C#6,您就可以使用它们,而不管您构建的.NET版本是什么。

在Visual Studio 2015中,您可以在Properties =>中控制要定位的语言版本。 Build tab => Advanced button => Language Version

答案 1 :(得分:3)

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

例如,这就是为什么您可以使用the Microsoft.Bcl.Async package在.Net 4.0上使用C#5.0 async - await

特别是对于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

您实际上可以通过引用the unofficial StringInterpolationBridge package来使其工作。