What do dollar symbols in C# Code mean?

大憨熊 提交于 2019-12-29 08:52:28

问题


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.


回答1:


The $ part tells the compiler that you want an interpolated string.

Interpolated strings are one of the new features of 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.

When the compiler encounters an interpolated string, it immediately converts it into a call to the String.Format function. 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.




回答2:


This is the new string interpolation introduced in C# 6



来源:https://stackoverflow.com/questions/31740340/what-do-dollar-symbols-in-c-sharp-code-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!