Tin*_*ter 5 .net c# string.format
根据文档,String.Format将抛出一个FormatExceptionif(A)格式字符串无效或(B)格式字符串包含在args数组中找不到的索引.
我希望能够确定任何字符串和参数数组中哪些(如果有)这些条件失败.
有什么能帮我的吗?谢谢!
跟进 gbogumil 的回答,在第一种情况下你会得到:
"Input string was not in a correct format."
Run Code Online (Sandbox Code Playgroud)
在第二个中,你得到:
"Index (zero based) must be greater than or equal to
zero and less than the size of the argument list."
Run Code Online (Sandbox Code Playgroud)
如果您需要感知哪个(用于用户消息传递或日志记录),那么您可以使用像 qor72 建议的 try catch ,并检查错误消息以什么开头。此外,如果您需要捕获格式字符串是什么以及参数是什么,您将需要执行以下操作:
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 );
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加了简单的正则表达式来计算格式标记。可能有帮助...
希望这可以帮助。祝你好运!