.NET 6常量内插字符串如何高效改写,实现长尾词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计508个文字,预计阅读时间需要3分钟。
目录+前言:+常量内嵌字符串+结论:+前言:+编写代码时,我们常常需要组合字符串。+代码示例:+string scheme=https;+string host=xxx.com;+int port=8080;+Console.WriteLine(string.Format({0}://{1}:{2}, scheme, host, port));
目录
- 前言:
- 常量内插字符串
- 结论:
前言:
编写代码时,我们常常需要组合字符串。
如下代码:
string scheme = "{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常量内插字符串内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
本文共计508个文字,预计阅读时间需要3分钟。
目录+前言:+常量内嵌字符串+结论:+前言:+编写代码时,我们常常需要组合字符串。+代码示例:+string scheme=https;+string host=xxx.com;+int port=8080;+Console.WriteLine(string.Format({0}://{1}:{2}, scheme, host, port));
目录
- 前言:
- 常量内插字符串
- 结论:
前言:
编写代码时,我们常常需要组合字符串。
如下代码:
string scheme = "{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常量内插字符串内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

