在C#中的命名字符串格式化 [英] Named string formatting in C#

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

问题描述

有没有办法在C#格式化字符串的名字,而不是位置?

Is there any way to format a string by name rather than position in C#?

在Python中,我可以做这样的事情的例子(从这里 无耻地窃取):

In python, I can do something like this example (shamelessly stolen from here):

>>> print '%(language)s has %(#)03d quote types.' % \
      {'language': "Python", "#": 2}
Python has 002 quote types.

有没有办法做到这一点在C#中?例如说:

Is there any way to do this in C#? Say for instance:

String.Format("{some_variable}: {some_other_variable}", ...);

由于能够使用一个变量名将是很好做,但一本字典是可以接受的了。

Being able to do this using a variable name would be nice, but a dictionary is acceptable too.

更新:最后我做这样的事情这个职位,但它绝对不是pretty的。我会尝试约翰·希恩的做法,但如果有人在此期间任何其他建议,可随时添加。 :)

UPDATE: I ended up doing something like this post, but it's definitely not pretty. I'll try out John Sheehan's approach, but if anybody has any other suggestions in the meantime, feel free to add them. :)

更新2:约翰·希恩的方法效果pretty的好。接受吧。

UPDATE 2: John Sheehan's approach works pretty well. Accepting it.

推荐答案

有处理这个没有内置的方法。

There is no built-in method for handling this.

这里有一个方法

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

<一个href="http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx">Here's另一个

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

<一个href="http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx">A第三改进的方法部分地基于上述两种时,从菲尔哈克

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

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