美元符号($“ string”)是什么 [英] What's with the dollar sign ($"string")

查看:168
本文介绍了美元符号($“ string”)是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在完成一本书中的一些C#练习,并且遇到了让我感到困惑的例子。直接从这本书开始,输出行显示为:

I have been running through some C# exercises in a book, and I ran across and example that stumped me. Straight from the book, the output line shows as:

Console.WriteLine($"\n\tYour result is {result}.");

现在我好像站起来了,代码起作用了,并且翻倍了如预期显示。但是,由于不理解为什么$出现在字符串的开头,我决定将其删除,现在代码输出数组名称 {result} 而不是内容。

Now I as if stands, the code works and the double result shows as expected. However, not understanding why the $ is there at the front of the string, I decided to remove it, and now the code outputs the name of the array {result} instead of the contents. The book doesn't explain why the $ is there, unfortunately.

我一直在搜寻VB 2015帮助和Google,有关字符串格式和Console.WriteLine重载方法。我没有看到任何能解释它为何如此的东西。任何建议将不胜感激。

I have been scouring the VB 2015 help and Google, regarding string formatting and Console.WriteLine overload methods. I am not seeing anything that explains why it is what it is. Any advice would be appreciated.

推荐答案

这是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.

这篇关于美元符号($“ string”)是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆