C#

使用内插字符串取代 string.format()

代码优化

Posted by Trojan on June 4, 2019

前言

C# 语言中的相关API 可以追溯到几十年前所诞生的C语言,但是这些老习惯应该改变,因为C# 6.0 提供了内插字符串 (Interpolated String) 这项新的功能可以用来更好地设置字符串的格式。

例子

Console.WriteLine($"The value of pi is {Math.PI}");  
// The value of pi is 3.14159265358979

内插字符串以 $ 开头,它不像传统的格式字符串那样把序号放在一对花括号里面,并用其指代 params 数组中的对应元素,而是可以直接在花括号里面编写 C# 表达式.

Console.WriteLine($"The value of pi is {Math.PI.ToString("F2")}"); 
// The value of pi is 3.14

在内插字符串中使用表尊的格式说明符(也就是 C# 语言内建的说明符)来调整字符串的格式。要实现该功能,只需在大括号的表达式后面加上冒号,并将格式说明符写在右侧。

Console.WriteLine($"The value of pi is {Math.PI:F2}"); 
// The value of pi is 3.14

如果在内插字符串里面使用冒号,那么C# 可能会把它理解成格式说明符的前导字符,而不是条件表达式。比如说,下面这行代码可能无法编译。

Console.WriteLine($"The value of pi is {true ? Math.PI.ToString() :Math.PI.ToString("F2")}");
解决方法很简单:加上括号就行了
Console.WriteLine($"The value of pi is {(flag ? Math.PI.ToString() :Math.PI.ToString("F2"))}");
// The value of pi is 3.14159265358979
还可以使用 null 合并运算符
Console.WriteLine($"The customer's name is {c?.Name ?? "Name is missing"}");
在内插字符串里面继续编写内插字符串
string result = default(string);
Dictionary<int, string> records = null;
var index = 1;
Console.WriteLine($@"Record is {(records.TryGetValue(index,out result)?result:$"No record found at index {index}")}");

如果要找的这条记录不存在,那么就会执行条件表达式的 false 部分,从而令那个小的内插字符串生效。

使用 LINQ 查询操作来创建内容
string src = "www.oulongixng.com";
var output = $@"The First five items are:{src.Take(6).Select(n => $@"Item :{n.ToString()}").Aggregate((c, a) => $@"{c}{Environment.NewLine}{a}")}";
Console.WriteLine(output);
/*

  The First five items are:Item :w
  Item :w
  Item :w
  Item :.
  Item :o
  Item :u
 */

参考

  • Effective C# (Third Edition)