给出以下方法:(真正的方法还有一些参数,但重要的参数如下......)
public string DoSomething(string formatter, params string[] values)
{
// Do something eventually involving a call to String.Format(formatter, values);
}
有没有办法判断我的值数组中是否有足够的对象来覆盖格式化程序,以便如果没有的话我可以抛出异常(缺少执行 string.Format ;这不是一个选项直到最后由于一些 lambda 转换)?
最佳答案
我仍然不清楚为什么你认为不能使用 string.Format
来测试它。如果传入的格式化程序应该具有值中项目的占位符,那么您应该能够执行以下操作:
static void TestFormat(string formatter, params string[] values)
{
try
{
string.Format(formatter, values);
}
catch (FormatException e)
{
throw new Exception("the format is bad!!", e);
}
}
用法示例:
TestFormat("{0}{1}{2}", "a", "b", "c"); // works ok
TestFormat("{0}{1}{2}", "a", "b"); // throws exception
TestFormat("{0}{1}{2}}0{", "a", "b", "c"); // throws exception
尝试使用正则表达式来做到这一点将会很困难,因为像这样的事情怎么样:
"{0}, {1}, {abc}, {1a4} {5} }{"
{abc}
和 {1a4}
对于 string.Format
无效,您还必须确定每个有效数字({0}, {1}, {5}
) 您至少有那么多参数。此外,}{
也会导致 string.Format 失败。
我刚刚在最近的一个项目中使用了上面描述的前一种方法,效果很好。
关于c# - 如何判断格式化字符串中的替换次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3057080/