String.Format
接收一个字符串参数format
值,以及params object[]
数组,可以处理任意大值的项。
对于每一个object
值,它是.ToString()
将调用方法来解析该格式模式
EDIT:看来我误读了你的问题。如果您想知道您的格式需要多少个参数,您可以通过使用正则表达式来发现:
string pattern = "{0} {1:00} {{2}}, Failure: {0}{{{1}}}, Failure: {0} ({0})";
int count = Regex.Matches(Regex.Replace(pattern,
@"(\{{2}|\}{2})", ""), // removes escaped curly brackets
@"\{\d+(?:\:?[^}]*)\}").Count; // returns 6
As Benjamin https://stackoverflow.com/users/59492/benjamin-podszun在评论中指出,也许您确实需要知道数量不同的参考。如果您不使用 Linq,请执行以下操作:
int count = Regex.Matches(Regex.Replace(pattern,
@"(\{{2}|\}{2})", ""), // removes escaped curly brackets
@"\{(\d+)(?:\:?[^}]*)\}").OfType<Match>()
.SelectMany(match => match.Groups.OfType<Group>().Skip(1))
.Select(index => Int32.Parse(index.Value))
.Max() + 1; // returns 2
这也地址@280Z28 https://stackoverflow.com/users/138304/280z28最后发现的问题。
280Z28 编辑:这不会验证输入,但对于任何有效的输入都会给出正确的答案:
int count2 =
Regex.Matches(
pattern.Replace("{{", string.Empty),
@"\{(\d+)")
.OfType<Match>()
.Select(match => int.Parse(match.Groups[1].Value))
.Union(Enumerable.Repeat(-1, 1))
.Max() + 1;