我仍然不清楚为什么你认为你不能用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 失败。
我刚刚在最近的一个项目中使用了上述前一种方法,效果很好。