C#代码中的美元符号是什么意思?
What do dollar symbols in C# Code mean?
今天从客户端拉取代码,这一行报错
throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");
这一行也
moreCompanies = $"{moreCompanies},{databaseName}";
$ 符号对我来说太奇怪了。这是 C# 代码。
这是 C# 6
中引入的新 string interpolation
$
部分告诉编译器你想要一个 interpolated string。
内插字符串是 C# 6.0 的新功能之一。它们允许您用相应的值替换字符串文字中的占位符。
您几乎可以将任何表达式放在内插字符串中的一对大括号 ({}
) 之间,并且该表达式将替换为该表达式结果的 ToString
表示形式。
当编译器遇到内插字符串时,它会立即将其转换为对 String.Format
函数的调用。正是因为如此,你的第一个listing本质上和写的一样:
throw new Exception(string.Format(
"One or more errors occured during removal of the company:{0}{1}{2}",
Envrionment.NewLine,
Environment.NewLine,
exc.Message));
如您所见,内插字符串允许您以更简洁的方式和更容易正确的方式表达同一事物。
今天从客户端拉取代码,这一行报错
throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");
这一行也
moreCompanies = $"{moreCompanies},{databaseName}";
$ 符号对我来说太奇怪了。这是 C# 代码。
这是 C# 6
中引入的新 string interpolation $
部分告诉编译器你想要一个 interpolated string。
内插字符串是 C# 6.0 的新功能之一。它们允许您用相应的值替换字符串文字中的占位符。
您几乎可以将任何表达式放在内插字符串中的一对大括号 ({}
) 之间,并且该表达式将替换为该表达式结果的 ToString
表示形式。
当编译器遇到内插字符串时,它会立即将其转换为对 String.Format
函数的调用。正是因为如此,你的第一个listing本质上和写的一样:
throw new Exception(string.Format(
"One or more errors occured during removal of the company:{0}{1}{2}",
Envrionment.NewLine,
Environment.NewLine,
exc.Message));
如您所见,内插字符串允许您以更简洁的方式和更容易正确的方式表达同一事物。