.net 6.0新特性 常量内插字符串

前言

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

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

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

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

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

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

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

常量内插字符串

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

.net 6.0新特性 常量内插字符串

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

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

const string FullName = #34;{FirstName} {LastName}";

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

.net 6.0新特性 常量内插字符串

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

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

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

结论

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

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

public void NewMethod() { }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 xxx@163.com 举报,一经查实,本站将立刻删除。

发表评论

登录后才能评论