如何判断格式化字符串中的替换次数?
给出以下方法:(真正的方法还有一些参数,但重要的参数如下...)
public string DoSomething(string formatter, params string[] values)
{
// Do something eventually involving a call to String.Format(formatter, values);
}
有没有办法判断我的值数组中是否有足够的对象来覆盖格式化程序,以便我可以抛出一个如果没有(缺少执行 string.Format ;由于某些 lambda 转换,直到最后都不是一个选项)?
Given the following method: (real method has a few more parameters, but the important ones are below...)
public string DoSomething(string formatter, params string[] values)
{
// Do something eventually involving a call to String.Format(formatter, values);
}
Is there a way to tell if my values array has enough objects in it to cover the formatter, so that I can throw an exception if there aren't (short of doing the string.Format; that isn't an option until the end due to some lambda conversions)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我仍然不清楚为什么您认为不能使用
string.Format
来测试它。如果传入的格式化程序应该具有值中项目的占位符,那么您应该能够执行以下操作:示例用法:
尝试使用正则表达式执行此操作将会很困难,因为像这样的事情怎么样:
< code>{abc} 和
{1a4}
对于string.Format
无效,您还必须确定每个有效数字 ({0}、{1}、{5}
)表明您至少有那么多参数。此外,}{
也会导致 string.Format 失败。我刚刚在最近的一个项目中使用了上面描述的前一种方法,效果很好。
I'm still not clear why you think you cannot use
string.Format
to test it. If the passed in formatter is supposed to have placeholders for the items in values, then you should be able to do this:Sample Usage:
Trying to do this with a regular expression is going to be tough, because what about something like this:
{abc}
and{1a4}
aren't valid forstring.Format
, and you also have to determine for each valid number ({0}, {1}, {5}
) that you have at least that many arguments. Also, the}{
will cause string.Format to fail as well.I just used the former approach described above in a recent project and it worked great.
我认为你对此担心太多了。如果格式字符串无效,让
string.Format
为您抛出异常。如果您不希望抛出FormatException
,请捕获它并抛出您想要的异常。您已经完成了一些处理(例如评估 lambda 转换)也不应该真正成为问题,因为这毕竟是一个例外情况(可能例外的是 lambda 非常昂贵,在这种情况下,首先执行
string.Format
测试而不处理参数以检查其是否有效,然后在处理后需要时重复该测试)。I think you are worrying too much about this. If the format string is invalid, let
string.Format
throw the exception for you. If you do not want aFormatException
to be thrown, catch it and throw the exception you want.It should also not really be a problem that you have already done some some processing (eg. evaluating lambda conversions) because this is after all an exceptional circumstance (with possibly the exception that the lambdas are very costly, in which case do the
string.Format
test first without processing the arguments to check it is valid and then repeat it when you need to later after the processing).使用正则表达式来计算模板的数量,但要小心,因为
它是有效的。
您确实需要提供更多信息才能回答这个问题......
Use a regex to count the number of templates, but be careful, because
is valid.
You really need to provide more info for this question to be answered ok...
您可以为大括号格式化程序执行正则表达式,然后将它们与值数组的长度进行比较。
You could do a RegEx for the brace formatters and then compare them to the length of the value array.