TryParse 为可空类型
我想尝试将 string
解析为 DateTime?
,如果失败,则将值设置为 null
。我能想到的唯一方法是以下,但它看起来不太整洁。
DateTime temp;
DateTime? whatIActuallyWant = null;
if (DateTime.TryParse(txtDate.Text, out temp)) whatIActuallyWant = temp;
这是唯一的方法吗?
I would like to try to parse a string
as a DateTime?
, and if it fails then set the value to null
. The only way I can think to do this is the following, but it doesn't seem very neat.
DateTime temp;
DateTime? whatIActuallyWant = null;
if (DateTime.TryParse(txtDate.Text, out temp)) whatIActuallyWant = temp;
Is this the only way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
你可以从中得到一行(不幸的是需要
DateTime?
强制转换,否则无法编译) - 但我个人可能会坚持使用null
初始化和随后的if
- 它更容易阅读。How about this:
You get a one-liner out of this (unfortunately need the
DateTime?
cast otherwise won't compile) - but personally I would probably stick to thenull
initialization and the subsequentif
- it's just easier to read.如果您要多次执行此操作,那么我建议添加一个简单的扩展方法以方便使用...
然后您可以非常轻松地使用它...
If your going to be performing this operation more than once then I recommend adding a simple extension method for ease of use...
Which you can then use very easily...