.NET 6新特性试用之常量内插字符串

Bianca ·
更新时间:2024-09-21
· 1913 次阅读

目录

前言:

常量内插字符串

结论:

前言:

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

如下代码:

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

​ 到此这篇关于.NET 6新特性试用之常量内插字符串的文章就介绍到这了,更多相关.NET 6常量内插字符串内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



字符 字符串 常量 .NET net

需要 登录 后方可回复, 如果你还没有账号请 注册新账号