且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

美元符号($“ string”)是什么

更新时间:2023-11-20 18:56:52

这是C#6中的新功能,称为内插字符串

It's the new feature in C# 6 called Interpolated Strings.

最简单的理解方法是:内插的字符串表达式通过用ToString替换包含的表达式来创建字符串表达式结果的表示形式。

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

有关此的更多详细信息,请查看 MSDN

For more details about this, please take a look at MSDN.

现在,请多考虑一点。 为什么此功能很棒?

Now, think a little bit more about it. Why this feature is great?

例如,您的课程 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 };

现在,您要将其输出到屏幕。常用的2种方式:

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

像这样串联字符串会使代码难以阅读且容易出错。您可以使用 string.Format()使其更好:

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

这会产生一个新问题:


  1. 您必须保持参数数量并自己建立索引。如果参数和索引的数目不同,则会生成运行时错误。

由于这些原因,我们应该使用new功能:

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

编译器现在为您维护占位符,因此您不必担心索引正确的参数因为只需将它放在字符串中就可以了。

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

有关完整的帖子,请阅读此博客

For the full post, please read this blog.