.NET 6 中的常量内插字符串

编写代码时,我们常常需要组合字符串。如下代码:

string scheme = "https";
string host = "xxx.com";
int port = 8080;

Console.WriteLine(string.Format("{0}://{1}:{2}", scheme, host, port));

但是,这种替换方式容易会产生错误,比如写错参数顺序,索引数字无效等。

因此,推荐的写法是使用字符串内插,代码如下:

Console.WriteLine($"{scheme}://{host}:{port}");

这样更容易阅读,而变量的值会被直接替换到字符串中。.

常量内插字符串

当所有字符串都是常量时,在.NET 6之前,是不能使用字符串内插的,只是使用+拼接字符串。

而在.NET 6,我们已经可以对常量使用内插字符串,代码如下:

const string FirstName = "My";
const string LastName = "IO";

const string FullName = $"{FirstName} {LastName}";

需要注意的是,内插字符串中的常量不能是数字

这是因为,数字常量转换为字符串是有区域性区分的,而区域性只有在运行时才能获得:

Console.WriteLine($"{1234.56}"); // output: 1234.56

Thread.CurrentThread.CurrentCulture= new CultureInfo("es-ES");
Console.WriteLine($"{1234.56}"); // output: 1234,56

对于Attribute使用参数时,常量内插字符串将非常方便,如下代码:

public class xxClass
{
    [Obsolete($"Use {nameof(NewMethod)} instead")]
    public void OldMethod() { }

    public void NewMethod() { }
}

这样,我们可以不用在Message中硬编码方法名称了。