如何确定复合格式字符串是否无效?
根据文档,String.Format
将如果 (A) 格式字符串无效或 (B) 格式字符串包含在 args 数组中找不到的索引,则抛出 FormatException
。
我希望能够确定这些条件中的哪些(如果有)在任意字符串和参数数组上失败。
有什么可以为我做到这一点吗?谢谢!
Per the documentation, String.Format
will throw a FormatException
if either (A) the format string is invalid or (B) the format string contains an index that cannot be found in the args array.
I want to be able to determine which (if either) of those conditions fail on any arbitrary string and array of arguments.
Is there anything that can do that for me? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
遵循 gbogumil 的答案,在第一种情况下,您会得到:
在第二种情况下,您会得到:
如果您需要感知哪个(用于用户消息传递或日志记录),那么您可以使用像 qor72 建议的 try catch ,并检查什么错误消息开头为。此外,如果您需要捕获格式字符串是什么以及参数是什么,您将需要执行如下操作:
编辑:添加了简单的正则表达式来计算格式标记。可能有帮助...
希望这有帮助。祝你好运!
Follow up to gbogumil's answer, in the first case you get:
and in the second, you get:
If you need to sense which (for user messaging or logging), then you could use a try catch like qor72 suggested, and check for what the error message starts with. In addition, if you need to capture what the format string was, and what the args were, you will need to do something like this:
EDIT: Added the simple regex to count format tokens. Might help...
Hope this helps. Good luck!
在每种情况下,FormatException 消息属性都设置为不同的消息。
The FormatException message property is set to a distinct message in each of those cases.
而你不想做...?
And you don't want to do...?
我最近使用下面的正则表达式来验证所有资源文件中的复合格式字符串
有关复合格式化字符串的详细信息,请参阅 http:// /msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx
I recently used the following regular expression below to validate the composite format strings in all our resources files
For more information about composite formatted strings, see http://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx