- ASP.NET Core 2 High Performance(Second Edition)
- James Singleton
- 259字
- 2021-07-08 09:38:58
String interpolation
String interpolation is a more elegant and easier-to-work-with version of the familiar string format method. Instead of supplying the arguments to embed in the string placeholders separately, you can now embed them directly in the string. This is far more readable and less error-prone.
Let's demonstrate this with an example. Consider the following code that embeds an exception in a string:
catch (Exception e)
{
Console.WriteLine("Oh dear, oh dear! {0}", e);
}
This embeds the first (and in this case only) object in the string at the position marked by zero. It may seem simple, but it quickly gets complex if you have many objects and want to add another at the start. You then have to correctly renumber all the placeholders.
Instead, you can now prefix the string with a dollar character and embed the object directly in it. This is shown in the following code that behaves the same as the previous example:
catch (Exception e)
{
Console.WriteLine($"Oh dear, oh dear! {e}");
}
The ToString() method on an exception outputs all the required information, including the name, message, stack trace, and any inner exceptions. There is no need to deconstruct it manually; you may even miss things if you do.
You can also use the same format strings as you are used to. Consider the following code that formats a date in a custom manner:
Console.WriteLine($"Starting at: {DateTimeOffset.UtcNow:yyyy/MM/dd HH:mm:ss}");
When this feature was being built, the syntax was slightly different. So, be wary of any old blog posts or documentation that may not be correct.
- R語言經典實例(原書第2版)
- Docker技術入門與實戰(第3版)
- C++面向對象程序設計(微課版)
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- 軟件品質之完美管理:實戰經典
- 新一代SDN:VMware NSX 網絡原理與實踐
- Learning Docker Networking
- Python趣味編程與精彩實例
- Learning Python Data Visualization
- 青少年學Python(第2冊)
- Appcelerator Titanium:Patterns and Best Practices
- The Python Apprentice
- Visual C++網絡編程教程(Visual Studio 2010平臺)
- RPA開發:UiPath入門與實戰
- PHP安全之道:項目安全的架構、技術與實踐