简体   繁体   English

C#代码中的美元符号是什么意思?

[英]What do dollar symbols in C# Code mean?

Today, I pull the code from my client, and I get an error in this line. 今天,我从客户端提取代码,并且在此行中遇到错误。

throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");

This line also 这条线也

moreCompanies = $"{moreCompanies},{databaseName}";

The $ symbols is so weird with me. $符号对我来说太奇怪了。 This is C# code. 这是C#代码。

The $ part tells the compiler that you want an interpolated string . $部分告诉编译器您需要插入的字符串

Interpolated strings are one of the new features of C# 6.0 . 插值字符串是C#6.0的新功能之一。 They allow you to substitute placeholders in a string literal with their corresponding values. 它们允许您用相应的值替换字符串文字中的占位符。

You can put almost any expression between a pair of braces ( {} ) inside an interpolated string and that expression will be substituted with the ToString representation of that expression's result. 您几乎可以将任何表达式放在插值字符串内的一对大括号( {} )之间,并且该表达式将替换为该表达式结果的ToString表示形式。

When the compiler encounters an interpolated string, it immediately converts it into a call to the String.Format function. 当编译器遇到插值的字符串时,它将立即将其转换为对String.Format函数的调用。 It is because of this that your first listing is essentially the same as writing: 正因为如此,您的第一个清单基本上与写作相同:

throw new Exception(string.Format(
    "One or more errors occured during removal of the company:{0}{1}{2}", 
    Envrionment.NewLine, 
    Environment.NewLine, 
    exc.Message));

As you can see, interpolated strings allow you to express the same thing in a much more succinct manner and in a way that is easier to get correct. 如您所见,内插字符串使您能够以更简洁的方式和更容易获得正确的方式来表达相同的事物。

这是C#6中引入的新字符串插值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM