.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之前,是不能使用字符串内插的,只是使用+拼接字符串:

25cc119f8b9b434dd1013891c02581d6.png

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

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

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

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

03f1765e06674ef3ca598efcdb28f7b9.png

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

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中硬编码方法名称了。

如果你觉得这篇文章对你有所启发,请帮忙点个或者在看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值