我可以检查格式说明符对于给定的数据类型是否有效吗?
如果我(在 .NET/C# 中)有一个 long
类型的变量,我可以将其转换为格式化字符串,例如:
long value = 12345;
string formattedValue = value.ToString("D10"); // returns "0000012345"
如果我指定的格式对该类型无效,我会得到一个异常:
long value = 12345;
string formattedValue = value.ToString("Q10"); // throws a System.FormatException
问题:在应用该格式之前,有没有办法检查格式说明符是否有效(除了尝试格式化和捕获异常),例如 long.IsFormatValid("Q10")
?
感谢您的帮助!
If I have (in .NET/C#) for instance a variable of type long
I can convert it to a formatted string like:
long value = 12345;
string formattedValue = value.ToString("D10"); // returns "0000012345"
If I specify a format which isn't valid for that type I get an exception:
long value = 12345;
string formattedValue = value.ToString("Q10"); // throws a System.FormatException
Question: Is there a way to check if a format specifier is valid (aside from trying to format and catching the exception) before I apply that format, something like long.IsFormatValid("Q10")
?
Thanks for help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还没有尝试过这个,但我认为你可以创建一个扩展方法,例如:
然后你可以这样应用它:
I've not tried this but I would think you could create an extension method such as:
which you could then apply thus:
我建议开发人员最好阅读 文档以了解哪些地方允许做什么。
但是,如果存在大量拼写错误的问题,我想您可以根据该页面上的信息编写一个查找表。尽管这可能会给你一种错误的安全感,因为你会让人们在有效的格式说明符之间犯错误(写一个
f
但他们的意思是e
等)。编辑以删除有关 TryParse/Parse 的混乱部分。
Rather than creating a check for that I'd suggest that it might be better that the developers reads the documentation to find out what's allowed where.
However, if there is a problem with a lot of typos being made, I suppose you could write a lookup table from the information on that page. Though that could just give you a false sense of security in that you'd get people making mistakes between valid format specifiers (writing an
f
but they meante
etc).Edited to remove confused bit about TryParse/Parse.