§ ITPOW >> 文档 >> C#

C# 的 $、@(插值与逐字)

作者:vkvi 来源:ITPOW(原创) 日期:2021-10-23

用微软官方的名字

$:string interpolation,字符串插值(也有称“内插”)。[ɪnˌtɜːrpəˈleɪʃn]

@:verbatim identifier,逐字标识符。[vɜːrˈbeɪtɪm] 

$:字符串插值

C# 中,有人使用 string.Format 的代替字符串相加,其实这个并不好,参数太自由,有点乱,而且效率也不高。

其实可以使用 $。

string s = $"姓名:{name}";

name 是一个变量,搞个 PHP 的一下就明白了,而且这里不单使用变量,还可使用属性啊、方法啊这些

结构

{<interpolationExpression>[,<alignment>][:<formatString>]}

前面的示例,我们只使用了表达式,还可以使用 formatString,比如:

{dateTime:yyyy-MM-dd}

还有一个不常用的 alignment,是个数值:

  • 正数:内容居右,左侧空格填充,使整个字符串达到指定的长度,类似于 PadLeft。

  • 负数:内容居左,左侧空格填充,使整个字符串达到指定的长度,类似于 PadRight。

微软的示例如下:

Console.WriteLine($"|{"Left",-7}|{"Right",7}|");

const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left   |  Right|
//     3.14159265358979 - default formatting of the pi number
//                3.142 - display only three decimal digits of the pi number

转义字符

{、} 被当作了特殊字符,如需要转义,请使用 {{、}}

: 也是分隔格式的特殊字符,所以在三目运算时,请用括号括起来

$"{(review ? "a" : "b")}"

@:逐字标识符

用法一、让关键词变成普通变量

string @for = "itpow";

如上,本来 for 是关键词,不能用作变量,但是我们加一个 @ 就可以,后面要用的时候,就按 @for 使用这个变量。

用法二、多行文本

string html = @"<table>
    <tr>
        <td class=""name""></td>
    </tr>
</table>";

如上,可以直接换行,写成多行了,省去写 \r\n,很是方便。

此时引号的转义字符,由 \ 变成了 ",即 " 变 ""。

用法三、解决属性名冲突

这个比较特殊,但是这个真不常用。

public class Info : Attribute
{
	public Info()
	{

	}
}
public class InfoAttribute : Attribute // 在某本书的规范要求中,建议对自定义属性添加 Attribute 后缀
{
	public InfoAttribute()
	{

	}
}

上述命名,第二个以 Attribute 结尾,这个很关键,假如我们对上述进行使用:

[Info()]
public static void Main()
{
}

这会有二义性的,编译通不过,我们改为:

[@Info()]
public static void Main()
{
}

[InfoAttribute()]
public static void Main2()
{
}

即:要使用短的(不带 Attribute)就加上 @,要使用长的(带 Attribute)那个,就使用的完整名称,就不会有歧义了。

另外,长的那个,你要加 @ 也可以,只是有点没必要。

$ 如何与 @ 同时使用呢?示例如下:

stringBuilder.Append($@"<li>
							<a href=""?id={item.Id}"">{HttpUtility.HtmlEncode(item.Title)}</a>
						</li>");

$ 在前,@ 在后。

Visual Studio 关于 @ 和 $ 的提示说反了

它把 @ 和 $ 说反了,如下:

它把 @ 和 $ 说反了

注意:从 C# 8.0 开始,@ 与 $ 的顺序就无所谓了。

相关文章