如何验证string.Format方法的格式

cod*_*ter 9 c# string.format

string.Format具有以下方法签名

string.Format(format, params, .., .. , ..);
Run Code Online (Sandbox Code Playgroud)

我想每次传递自定义格式

string custFormat = "Hi {0} ... {n} ";   // I only care about numbers here, and want avoid  {abdb}
string name = "Foo";

string message = ProcessMessage(custFormat, name);

public string ProcessMessage(custFormat, name)
{
   return string.Format(custFormat, name);
}
Run Code Online (Sandbox Code Playgroud)

我想在传递给ProcessMessage之前验证custFormat中的值以避免异常.

lat*_*kin 20

让我们考虑一下这个API,如果它存在的话.目标是预先验证格式字符串,以确保String.Format不会抛出.

请注意,任何包含有效格式槽的字符串都是有效的格式字符串 - 如果您不尝试插入任何替换.

- >所以我们需要传递我们期望替换的数字或参数

请注意,有大量不同的特殊格式模式,每种模式都具有特定类型的特定含义:http://msdn.microsoft.com/en-us/library/system.string.format.aspx

虽然String.Format如果传递的格式字符串与您的参数类型不匹配似乎不会抛出,但在这种情况下,格式化程序变得毫无意义.例如String.Format("{0:0000}", "foo")

- >因此,只有在传递了args的类型时,这样的API才真正有用.

如果我们已经需要传入我们的格式字符串和一个类型数组(至少),那么我们基本上是签名String.Format,那么为什么不使用它并处理异常呢?如果String.TryFormat存在类似的东西会很好,但据我所知,它不存在.

此外,通过某些API进行预验证,然后重新验证String.Format本身并不是理想的.

我认为最干净的解决方案可能是定义一个包装器:

public static bool TryFormat(string format, out string result, params Object[] args)
{
   try
   {
      result = String.Format(format, args);
      return true;
   }
   catch(FormatException)
   {
      return false;
   }
}
Run Code Online (Sandbox Code Playgroud)