什么是C#字符串的$修饰符

时间:2015-12-24 06:27:39

标签: c# .net string

这个问题听起来与此相似:

What's the @ in front of a string in C#?

但是我已经意识到C#中字符串文字前面@ -character的含义。

但是现在我在一个例子中看到了这个:

var xml = $@"<toast>
    <visual>
        <binding template='ToastGeneric'>
            <text>text</text>
        </binding>
    </visual>

    <audio src='ms-winsoundevent:Notification.Looping.Alarm10' loop='true'/>
</toast>";

@还有额外的$。这是什么意思?

2 个答案:

答案 0 :(得分:5)

它的interpolated string,C#6.0的新功能(https://msdn.microsoft.com/en-us/library/dn961160.aspx

基本上,它会替换旧C#版本中的string.Format("", params);

使用示例:

var str = "test";
var xml = $@"<toast>
    <visual>
        <binding template='ToastGeneric'>
            <text>{str}</text>
        </binding>
    </visual>
    <audio src='ms-winsoundevent:Notification.Looping.Alarm10' loop='true'/>
</toast>";

答案 1 :(得分:1)

$符号表示C#中的插值字符串。

MSDN: https://msdn.microsoft.com/en-us/library/dn961160.aspx

用法示例:

string zzz = "world";
string helloWorld = $"hello {zzz}"; // hello world

代码中的字符串中没有花括号,因此不会发生实际值注入 - 您可以删除$并仍然获得相同的结果。