我在一本书中经历了一些C#练习,然后我遇到了一些难以理解的例子.直接从书中,输出线显示为:
Console.WriteLine($"\n\tYour result is {result}.");
Run Code Online (Sandbox Code Playgroud)
现在我好像站着,代码工作和double result
节目如预期的那样.但是,不理解$为什么在字符串的前面,我决定删除它,现在代码输出数组的名称{result}
而不是内容.不幸的是,这本书没有解释为什么$存在.
关于字符串格式化和Console.WriteLine重载方法,我一直在搜索VB 2015帮助和谷歌.我没有看到任何解释为什么它是什么的东西.任何意见,将不胜感激.
Tri*_*oan 342
这是C#6中的新功能Interpolated Strings
.
理解它的最简单方法是:插值字符串表达式通过用表达式结果的ToString表示替换包含的表达式来创建字符串.
有关这方面的更多详细信息,请查看MSDN.
现在,再考虑一下.为什么这个功能很棒?
例如,你有课Point
:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
创建2个实例:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point {X = 7, Y = 3};
Run Code Online (Sandbox Code Playgroud)
现在,您想将其输出到屏幕.您经常使用的两种方式:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,连接这样的字符串会使代码难以阅读且容易出错.您可以使用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));
Run Code Online (Sandbox Code Playgroud)
这会产生一个新问题:
出于这些原因,我们应该使用新功能:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
Run Code Online (Sandbox Code Playgroud)
编译器现在为您维护占位符,因此您不必担心索引正确的参数,因为您只需将其放在字符串中.
有关完整帖子,请阅读此博客.
Moh*_*ava 50
像Perl这样的语言已经存在了很长一段时间的概念,现在我们也将在C#中获得这种能力.在String Interpolation中,我们只需在字符串前加上$(就像我们使用@作为逐字字符串一样).然后,我们简单地用大括号(即{和})包围我们想要插入的表达式:
它看起来很像String.Format()占位符,但它不是索引,而是花括号内的表达式.实际上,它看起来像String.Format()应该不足为奇,因为它实际上就是它 - 编译器在后台处理像String.Format()这样的语法糖.
很重要的是,编译器现在为您维护占位符,因此您不必担心索引正确的参数,因为您只需将其放在字符串中.
阅读更多关于C#/ .Net Little Wonders:C#6中的字符串插值