这是c# 6中的新特性,称为插值字符串。
理解它最简单的方法是:插值字符串表达式通过将包含的表达式替换为表达式结果的ToString表示来创建字符串。
欲了解更多细节,请参阅MSDN。
现在,再想一下。为什么这个功能很棒?
例如,你有一个类Point:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
创建2个实例:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
现在,你想把它输出到屏幕上。你通常使用的两种方法:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
如您所见,这样的串接字符串使代码难以阅读且容易出错。你可以使用string.Format()来使它更好:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
这就产生了一个新问题:
您必须自己维护参数的数量和索引。如果参数和索引的数量不相同,它将生成一个运行时错误。
基于这些原因,我们应该使用新的特性:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
编译器现在为你维护占位符,所以你不必担心索引正确的参数,因为你只是把它放在字符串中。
完整的文章,请阅读这个博客。