该值是有效的年份 C#
使用 C# 检查字符串是否为有效年份的最佳方法是什么?
我目前有一个包含值 {'All','2009','2008'} 等的下拉列表,我想知道选择的是日期之一还是“All”字段。
目前我正在检查 bool isYearValid = (Year.ToLower() == "all") ? false : true;
如何检查该值是否为有效年份,以便不必对“全部”进行硬编码检查?
What's the best way to check if a string is a valid year using C#?
I currently have a dropdown list that contains the values {'All','2009','2008'} etc, and I want to know whether the selection is one of the dates or the 'All' field.
Currently I'm checking for bool isYearValid = (Year.ToLower() == "all") ? false : true;
How do I check whether the value is a valid year so that I don't have to have this hardcoded check for 'All'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以尝试将年份解析为整数:
You can try parsing the year as an integer:
鉴于年份只需是一个有效的数字,您可以只使用 int32.TryParse,然后根据您希望年份所处的范围简单地检查范围。
Given that a year simply needs to be a valid number, you could just use int32.TryParse and then simply check the range based on what range you want the year to be in.
你可以使用:
you could use:
无论如何,这不是更好吗?
Wouldn't this be better anyway?
怎么样:
这样您就不必在验证点手动检查“全部”。在实际实现时,您仍然需要检查 1900,但无论如何,现在肯定有办法避免使那成为一个特殊的场景。
除此之外,
DateTime.TryParse
是确定字符串表示形式是否为有效日期的正确方法。How about:
That way you don't have to manually check for "All" at the validation point. You still need to check for 1900, when actually implementing this, but there'd definitely be now way to avoid making that a special scenario, anyway.
Other than that,
DateTime.TryParse
is the proper way to find out if a string representation is a valid date.好吧,没有人提到它,但为什么不定义一个“All”符号
某处并在下拉初始化和比较中使用它?
Well, no-one's mentioned it, but why not have a symbol for 'All' defined
somewhere and use that in both the drop down initialisation and the comparison?