string.Format()与它的"bla {0} bla"语法很棒.但有时候我不想列举占位符.相反,我只想在占位符中按顺序映射变量.有没有可以做到这一点的图书馆?
例如,而不是
string.Format("string1={0}, string2={1}", v1, v2)
Run Code Online (Sandbox Code Playgroud)
就像是
string.Format("string1={*}, string2={*}", v1, v2)
Run Code Online (Sandbox Code Playgroud)
ozz*_*836 11
现在在C#6.0中有一个叫做字符串插值的东西
var name = "ozzy";
var x = string.Format("Hello {0}", name);
var y = $"Hello {name}";
Run Code Online (Sandbox Code Playgroud)
等同于同一件事.
请参阅https://msdn.microsoft.com/en-gb/magazine/dn879355.aspx
这是一个可能更快的版本使用Regex.Replace.警告:当你超出范围或者没有提供足够的参数时,不支持转义{*}或错误消息!
public static class ExtensionMethods
{
private static Regex regexFormatSeq = new Regex(@"{\*}", RegexOptions.Compiled);
public static string FormatSeq(this string format, params object[] args)
{
int i = 0;
return regexFormatSeq.Replace(format, match => args[i++].ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
假设您使用的是 .NET 3.5 或更高版本,您可以通过编写自己的字符串扩展以及 params 关键字来自行完成此操作。
编辑:很无聊,代码很草率并且容易出错,但是将此类放入您的项目中并在必要时使用其名称空间:
public static class StringExtensions
{
public static string FormatEx(this string s, params string[] parameters)
{
Regex r = new Regex(Regex.Escape("{*}"));
for (int i = 0; i < parameters.Length; i++)
{
s = r.Replace(s, parameters[i], 1);
}
return s;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Console.WriteLine("great new {*} function {*}".FormatEx("one", "two"));
Run Code Online (Sandbox Code Playgroud)