如何根据 C# 的目标参数类型验证复合格式字符串?
给定用户提供的复合格式字符串(与 String.Format 一起使用)和一组表示将用于格式化复合格式字符串的参数的类型,如何检查用户是否- 提供的值有效吗?
创建正则表达式来检查参数占位符的一般语法是否与每个 文档。 并且验证复合格式字符串中占位符的索引是否小于类型化参数的实际数量(即它们不引用不会给出的参数)并没有太困难。 但是,鉴于将传入的参数的类型已知,还应该可以验证“:formatString
”是否适合这些类型。
例如,当第一个参数类型(0 索引)为数字(String. Format("{0:dddd MMMM}", 1234)
生成“dddd MMMM
”)。 按类型划分的“:formatString
”选项的数量为 太大,无法手动检查所有内容。 还有其他办法吗? 或者您是否只需要忍受用户可能指定错误的格式字符串?
假设没有自定义 IFormatProvider
、ICustomFormatter
或 < a href="http://msdn.microsoft.com/en-us/library/system.iformattable.aspx" rel="nofollow noreferrer">IFormattable
实现在这里发挥作用。 只是 .NET Framework 中已有的基本类型。 解决自定义问题的奖励积分。
Given a composite format string provided by the user (for use with String.Format
) and a set of types representing the arguments that would be used to format the composite format string, how can you check that the user-provided value is valid?
It should be pretty easy to create a regular expression to check that the general syntax of the argument placeholders match "{index[,alignment][:formatString]}
" per the documentation. And not too much more difficult to verify that the indexes of the placeholders in the composite format string are less than the actual number of typed arguments (i.e. they don't reference an argument that won't be given). However, given the types for the arguments that will be passed in are known, it should also be possible to validate the ":formatString
" is appropriate for those types.
For example, you want to validate the user doesn't specify "{0:dddd MMMM}
" as a format string when the first argument type (0 index) is a number (String.Format("{0:dddd MMMM}", 1234)
yields "dddd MMMM
"). The quantity of ":formatString
" options by type is too large to want to manually check everything. Is there any other way? Or do you just have to live with the user potentially specifying a bad format string?
Assume there are no custom IFormatProvider
, ICustomFormatter
or IFormattable
implementations in play here. Just basic types already in the .NET Framework. Bonus points for addressing the custom stuff.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,没有内置的方法可以做到这一点。
您可以手动对每个常见情况进行编码,但我不推荐这样做。
(编辑)一个实用的选项可能是
try/catch
- 当用户输入格式时尽早测试格式......There is no inbuilt way of doing this, AFAIK.
You could code every common case manually, but I don't recommend it.
(edit) One pragmatic option might be
try/catch
- test the format as early as possible when the user enters it....抱歉,但这样做的方法是:
是的,有点糟糕。
Sorry, but the way to do it is:
Yep, kinda bad.
如果用户指定的错误格式字符串可能会导致异常,那么也许您可以尝试一下? 是的,这是一个幼稚而琐碎的想法。
If bad format string specified by user could cause exception, then maybe you can just try it out? Yes, it's naive and trivial idea.