命名为String.Format,可能吗?
我想使用 {title}
代替 {0} {1}
等。 然后以某种方式填充该数据(下面我使用了字典
)。 此代码无效并引发异常。 我想知道我是否可以做一些与我想要的类似的事情。 使用 {0 .. N}
不是问题。 我只是好奇而已。
Dictionary<string, string> d = new Dictionary<string, string>();
d["a"] = "he";
d["ba"] = "llo";
d["lol"] = "world";
string a = string.Format("{a}{ba}{lol}", d);
Instead of using {0} {1}
, etc. I want to use {title}
instead. Then fill that data in somehow (below I used a Dictionary
). This code is invalid and throws an exception. I wanted to know if i can do something similar to what i want. Using {0 .. N}
is not a problem. I was just curious.
Dictionary<string, string> d = new Dictionary<string, string>();
d["a"] = "he";
d["ba"] = "llo";
d["lol"] = "world";
string a = string.Format("{a}{ba}{lol}", d);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
不,但是这个扩展方法可以做到
No, but this extension method will do it
查一下这个,支持格式化:
使用方法:
Check this one, it supports formating:
How to use:
您可以实现自己的:
You can implement your own:
现在可以
使用 C# 6.0 的插值字符串,您可以执行以下操作:
It's possible now
With Interpolated Strings of C# 6.0 you can do this:
比其他扩展方法涉及更多一点,但这也应该允许在它们上使用非字符串值和格式模式,因此在您的原始示例中:
也可以工作...
A little more involved than the other extension method, but this should also allow non-string values and formatting patterns used on them, so in your original example:
Will also work...
自 C# 6 发布以来,您可以使用 字符串插值功能
解决您问题的代码:
Since C# 6 released you are able to use String Interpolation feature
Code that solves your question:
为什么要有字典? 这是不必要的并且过于复杂。 一个简单的名称/值对的二维数组也可以工作:
使用以下命令调用上面的
结果:
“Dictionary =不必要(实际上,它是不必要的)”
Why a Dictionary? It's unnecessary and overly complicated. A simple 2 dimensional array of name/value pairs would work just as well:
Call the above with:
Results in:
"Dictionary = unnecessary (really, it's unnecessary)"
这与另一个答案类似,但它考虑使用 {{text}} 进行转义。
This is similar to another answer, but it considers escaping with {{text}}.
我采用了@LPCRoy的答案并针对通用字典类型进行了重构,添加了参数验证,它仅替换它可以找到的字段,并尝试通过首先转义它们来解决“双花括号”问题,然后在末尾用单大括号替换它们与 string.Format() 的方式相同。
I took @LPCRoy's answer and refactored for generic dictionary types, added parameter validation, it only replaces fields it can find, and attempts to solve the "double curly brace" issue by escaping them first, then replacing them at the end with single braces in the same way that string.Format() does.
这是一个很好的解决方案,在格式化电子邮件时非常有用: http://www.c-sharpcorner.com/UploadFile/e4ff85/string-replacement-with-named-string-placeholders/
编辑:
示例用法:
Here is a nice solution that is very useful when formatting emails: http://www.c-sharpcorner.com/UploadFile/e4ff85/string-replacement-with-named-string-placeholders/
Edited:
Example usage:
(你的 Dictionary + foreach + string.Replace)包裹在子例程或扩展方法中?
显然没有优化,但是......
(your Dictionary + foreach + string.Replace) wrapped in a sub-routine or extension method?
Obviously unoptimized, but...