C#:可以使用String.Format来代替数字吗?
参考此链接
http://msdn.microsoft.com/en-us/library/b1csw23d.aspx
看起来String.Format方法不可能在格式字符串参数中使用标签而不是索引。
.Net Framework是否有一些原生的语法或function允许使用标签而不是0,1,…,N?
作为一个例子,这怎么可能:
Console.WriteLine(String.Format("{0}{1}{0}{1}", "foo", "bar"));
成为这样的事情:
Console.WriteLine(String.Format("{foo}{bar}{foo}{bar}", new { foo = "foo", bar = "bar" }));
打开reflection器后的好问题
没有办法:
它仅以数字计数:
Phil Haack写了一篇关于如何做到这一点的博客:
http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx
.NET中没有内置的方法来实现这一点。
Ref: C#:String.Inject() – 按键令牌格式化字符串
string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
它接受一个对象,IDictionary或HashTable,并用实例值替换属性名称/密钥标记。 由于它在内部使用string.Format,因此它使用类似string.Format的自定义格式 。
.Net内部没有这样的实现。 您可以使用自定义格式与ICustomFormatProvider接口 。
格式项的语法如下:
{index[,length][:formatString]}
从C#6开始,您可以使用Interpolated Strings :
string foo = "foo1"; string bar = "bar2"; Console.WriteLine($"{foo} {bar} {foo} {bar}");
哪个会输出:
foo1 bar2 foo1 bar2