Using string interpolation and nameof in .VS 2015

2019-04-06 22:59发布

问题:

I'm using things like $"hello {person}" and nameof(arg1) in my code, but on checking the project properties I'm targeting .NET 4.5.

Is this okay? I thought these things were introduced in 4.6.

The project builds and runs okay on my machine - but I'm worried something will go wrong when I deploy it.

回答1:

It's a compiler feature, not a framework feature. We successfully use both features with our .NET 3.5 projects in Visual Studio 2015.

In a nutshell, the compiler translates $"hello {person}" to String.Format("hello {0}", person) and nameof(arg1) to "arg1". It's just syntactic sugar.

The runtime sees a String.Format call (or a string literal "arg1", respectively) and does not know (nor care) what the original source code looked like. String.Format is supported since the early days of the .NET Framework, so there's nothing preventing you from targeting an earlier version of the framework.



回答2:

The existing answers talk about this being a C# 6 feature without a .NET framework component.

This is entirely true of nameof - but only somewhat true of string interpolation.

String interpolation will use string.Format in most cases, but if you're using .NET 4.6, it can also convert an interpolated string into a FormattableString, which is useful if you want invariant formatting:

using System;
using System.Globalization;
using static System.FormattableString;

class Test
{
    static void Main()
    {
        CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        double d = 0.5;
        string local = $"{d}";
        string invariant = Invariant($"{d}");
        Console.WriteLine(local);     // 0,5
        Console.WriteLine(invariant); // 0.5
    }    
}

Obviously this wouldn't work if $"{d}" simply invoked a call to string.Format... instead, in this case it calls string.Format in the statement assigning to local, and calls FormattableStringFactory.Create in the statement assigning to invariant, and calls FormattableString.Invariant on the result. If you try to compile this against an earlier version of the framework, FormattableString won't exist so it won't compile. You can provide your own implementation of FormattableString and FormattableStringFactory if you really want to, though, and the compiler will use them appropriately.



回答3:

These things were introduced in C#6. .Net has nothing to do with it. So as long as you are using a C#6 compiler, you can use these features.

What is the difference between C# and .NET?

So yes, it is okay to use them in a project targeting .Net 4.5.