C#中的命名字符串格式 [英] Named string formatting in C#
本文介绍了C#中的命名字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 C# 中按名称而不是位置来格式化字符串?
在 python 中,我可以做类似这个例子的事情(无耻地从 here):
<预><代码>>>>打印 '%(language)s 有 %(#)03d 个引号类型.'% {'语言':Python",#":2}Python 有 002 种引用类型.在 C# 中有没有办法做到这一点?比如说:
String.Format("{some_variable}: {some_other_variable}", ...);
能够使用变量名来做到这一点会很好,但字典也是可以接受的.
解决方案
没有处理这个的内置方法.
string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
Status.Text = "{UserName} 最后登录时间为 {LastLoginDate}".FormatWith(user);
部分基于上述两种方法的第三种改进方法,来自 Phil Haack
Is there any way to format a string by name rather than position in C#?
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.
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.
解决方案
There is no built-in method for handling this.
string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);
A third improved method partially based on the two above, from Phil Haack
这篇关于C#中的命名字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文