Ill*_*ych 4 c# string interpolation string-interpolation
有没有办法在不重复的情况下多次插值变量?
例如:
var name = "bla";
Console.WriteLine($"foo {name:repeat:2} bar")
Run Code Online (Sandbox Code Playgroud)
打印
foo blabla bar
Run Code Online (Sandbox Code Playgroud)
我特别感兴趣的是插入几个换行符而不是{Environment.NewLine}在插值掩码中重复几次,如下所示:
$"{Environment.NewLine}{Environment.NewLine}"
Run Code Online (Sandbox Code Playgroud)
public static string Repeat(this string s, int times, string separator = "")
{
return string.Join(separator, Enumerable.Repeat(s, times));
}
Run Code Online (Sandbox Code Playgroud)
然后使用:
Console.WriteLine($"foo {name.Repeat(2)} bar")
Run Code Online (Sandbox Code Playgroud)