且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 13:28:16

$ 部分告诉编译器您需要插值字符串是的新功能之一C#6.0 .它们允许您用相应的值替换字符串文字中的占位符.

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.

您几乎可以将任何表达式放在插值字符串内的一对大括号( {} )之间,并且该表达式将替换为该表达式结果的 ToString 表示形式

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.

当编译器遇到插值字符串时,它将立即将其转换为对 String.Format 函数的调用.正因为如此,您的第一个清单基本上与写作相同:

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.