多行C#插值字符串

编程入门 行业动态 更新时间:2024-10-22 08:41:03
本文介绍了多行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();

或者是有什么更优雅?

解决方案

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

字符串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#插值字符串

本文发布于:2023-11-08 14:02:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   插值   多行

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!