c# - 如何判断格式化字符串中的替换次数?

标签 c# testing formatting params-keyword

给出以下方法:(真正的方法还有一些参数,但重要的参数如下......)

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/

相关文章:

c# - 验证所有值

c# - .Net 流 : Returning vs Providing

javascript - Javascript可以用来格式化HTML吗

algorithm - 模糊日期算法

c# - 如何强制注销网站的所有用户?

javascript - 为什么我的 ajax 调用无法到达我的 .NET WebMethod?

ruby-on-rails - Cucumber/Capybara/Selenium - 设置 cookie

testing - Selenium:无法点击类和图像

testing - 如何组织软件不同版本的测试用例?

java - 使用 java 以编程方式格式化 java 代码