多行C#插值字符串 [英] Multiline C# interpolated string literal

查看:158
本文介绍了多行C#插值字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#6带来了插值字符串与语法的编译器支持:

 变种人=新{名称=鲍勃} ; 

字符串s = $你好,{} person.Name。

这是伟大的短字符串,但如果你想制作一个更长的字符串,它必须得到指定的一行



使用其他类型的字符串,您可以:?

  VAR multi1 =的String.Format(@身高:{0} 
宽度:{1}
背景:{2},
高度,
宽度,
背景);

或者



  VAR MULTI2 =的String.Format(
身高:{1} {0}+
宽度:{2} {0}+
背景:{ 3},
Environment.NewLine,
高度,
宽度,
背景);



我不能找到一种方法,而无需一切一一符合字符串插值来实现:

  VAR MULTI3 = $身高:{高度} {} Environment.NewLine宽度:宽度{} {} Environment.NewLine背景: {背景}; 



我意识到,在这种情况下,你可以使用 \r\\\
Environment.NewLine 的(不便携式),或将其拉出到本地,但会有这样的情况,你不能减少它下面又不失语义强度一行。



难道仅仅是串插不应该被用于长字符串的情况?



难道只用字符串的StringBuilder 更长的字符串?

  VAR multi4 =新的StringBuilder()
.AppendFormat(宽度:{0},宽度).AppendLine()
.AppendFormat(身高:{0},高度).AppendLine( )
.AppendFormat(背景:{0},背景).AppendLine()
的ToString();



或者是有什么更优雅?


解决方案

您可以将 $ @ 合力得到多行插入字符串文字:



<预类=郎无prettyprint-覆盖> 字符串s =
$ @身高:{高度}
宽度:宽度{}
背景:{}背景;

来源:在C#6 长字符串插线(感谢 @Ric 寻找线程!)


C# 6 brings compiler support for interpolated string literals with syntax:

var person = new { Name = "Bob" };

string s = $"Hello, {person.Name}.";

This is great for short strings, but if you want to produce a longer string must it be specified on a single line?

With other kinds of strings you can:

    var multi1 = string.Format(@"Height: {0}
Width: {1}
Background: {2}",
        height,
        width,
        background);

Or:

var multi2 = string.Format(
    "Height: {1}{0}" +
    "Width: {2}{0}" +
    "Background: {3}",
    Environment.NewLine,
    height,
    width,
    background);

I can't find a way to achieve this with string interpolation without having it all one one line:

var multi3 = $"Height: {height}{Environment.NewLine}Width: {width}{Environment.NewLine}Background: {background}";

I realise that in this case you could use \r\n in place of Environment.NewLine (less portable), or pull it out to a local, but there will be cases where you can't reduce it below one line without losing semantic strength.

Is it simply the case that string interpolation should not be used for long strings?

Should we just string using StringBuilder for longer strings?

var multi4 = new StringBuilder()
    .AppendFormat("Width: {0}", width).AppendLine()
    .AppendFormat("Height: {0}", height).AppendLine()
    .AppendFormat("Background: {0}", background).AppendLine()
    .ToString();

Or is there something more elegant?

解决方案

You can combine $ and @ together to get a multiline interpolated string literal:

string s =
$@"Height: {height}
Width: {width}
Background: {background}";

Source: Long string interpolation lines in C#6 (Thanks to @Ric for finding the thread!)

这篇关于多行C#插值字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆