C#:可以使用String.Format来代替数字吗?

时间:2012-03-20 11:47:27

标签: c# .net

参考此链接

http://msdn.microsoft.com/en-us/library/b1csw23d.aspx

似乎String.Format方法无法在格式字符串参数中使用标签而不是索引。

.Net Framework是否有一些原生的语法或功能允许使用标签而不是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" }));

4 个答案:

答案 0 :(得分:4)

菲尔·哈克(Phil Haack)写了一篇关于如何做到这一点的博客:

http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx

.NET中没有内置的方法来实现这一目标。

答案 1 :(得分:1)

好的问题 打开反射器后

没有办法:

仅以数字计算:

enter image description here

答案 2 :(得分:1)

参考:C#: String.Inject() - Format strings by key tokens

string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);

它接受一个对象,IDictionary或HashTable,并用实例值替换属性name / key tokens。由于它在内部使用string.Format,因此它使用string.Format-like custom formatting

  

.Net内部没有这样的实现。您可以使用   Custom formatting with ICustomFormatProvider Interface

     

格式项的语法如下:

{index[,length][:formatString]}

答案 3 :(得分:1)

从C#6开始,您可以使用Interpolated Strings

string foo = "foo1";
string bar = "bar2";
Console.WriteLine($"{foo} {bar} {foo} {bar}");

将输出:

  

foo1 bar2 foo1 bar2

相关问题