5

根据文档,如果 (A) 格式字符串无效或 (B) 格式字符串包含在 args 数组中找不到的索引,String.Format则会抛出一个。FormatException

我希望能够确定哪些条件(如果有的话)在任意字符串和参数数组上失败。

有什么可以为我做的吗?谢谢!

4

4 回答 4

2

跟进 gbogumil 的回答,在第一种情况下,您会得到:

"Input string was not in a correct format."

在第二个中,你得到:

"Index (zero based) must be greater than or equal to 
zero and less than the size of the argument list."

如果您需要感知哪个(用于用户消息传递或日志记录),那么您可以使用 qor72 建议的 try catch,并检查错误消息的开头。此外,如果您需要捕获格式字符串是什么以及 args 是什么,则需要执行以下操作:

        string myStr = "{0}{1}{2}";
        string[] strArgs = new string[]{"this", "that"};
        string result = null;

        try { result = string.Format(myStr, strArgs); }

        catch (FormatException fex)
        {
            if (fex.Message.StartsWith("Input"))
                Console.WriteLine
                  ("Trouble with format string: \"" + myStr + "\"");
            else
                Console.WriteLine
                  ("Trouble with format args: " + string.Join(";", strArgs));
            string regex = @"\{\d+\}";
            Regex reg = new Regex(regex, RegexOptions.Multiline);
            MatchCollection matches = reg.Matches(myStr);
            Console.WriteLine
                ("Your format has {0} tokens and {1} arguments", 
                 matches.Count, strArgs.Length );

        }

编辑:添加了简单的正则表达式来计算格式标记。可能有帮助...

希望这可以帮助。祝你好运!

于 2010-04-16T20:02:59.120 回答
1

在每种情况下,FormatException 消息属性都设置为不同的消息。

于 2010-04-16T19:32:55.953 回答
0

而你不想做...?

works = true;
try {
  String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
于 2010-04-16T19:33:31.553 回答
0

我最近使用下面的正则表达式来验证我们所有资源文件中的复合格式字符串

    /// <summary>
    /// The regular expression to get argument indexes from a composed format string
    /// </summary>
    /// <remarks> 
    /// example         index   alignment   formatString
    /// {0}             0       
    /// {1:d}           1                   d
    /// {2,12}          2       12
    /// {3,12:#}        3       12          #
    /// {{5}}           
    /// {{{6}}}         6
    /// </remarks>
    private static readonly Regex ComposedFormatArgsRegex =
        new Regex(@"(?<!(?<!\{)\{)\{(?<index>\d+)(,(?<alignment>\d+))?(:(?<formatString>[^\}]+))?\}(?!\}(?!\}))",
            RegexOptions.Compiled | RegexOptions.ExplicitCapture);

有关复合格式字符串的更多信息,请参阅http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx

于 2014-02-24T15:45:05.620 回答