c# - C#中的命名字符串格式化

标签 c# .net-3.5 string-formatting

有没有办法在 C# 中按名称而不是位置来格式化字符串?

在 python 中,我可以做类似这个例子的事情(无耻地从 here 偷来的):

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

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

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

能够使用变量名来执行此操作会很好,但字典也是可以接受的。

最佳答案

没有用于处理此问题的内置方法。

Here's one method

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

Here's another

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

A third improved method partially based on the two above , 来自菲尔哈克

关于c# - C#中的命名字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/159017/

相关文章:

c# - 消息队列思想

c++ - 如何使用 C++20 std::format?

c# - 在 String.Format 中每两位数字后添加逗号

c# - 是否可以在 FileSystemWatcher 上设置间隔?

c# - WCF 错误 - 安全处理器无法在消息中找到安全 header

Python:使用 string.format() 将单词大写

c# - 带复选框的 .NET TreeView 控件

c# - 检测 Windows 服务中注销的用户

c# - 通过 app.config 关闭跟踪

c# - 为什么从 Async CTP/Release 中删除 "SwitchTo"?