在三元运算中将null / Nullable分配给DateTime [英] Assigning null/Nullable to DateTime in Ternary Operation

查看:93
本文介绍了在三元运算中将null / Nullable分配给DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条语句,

DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);

我无法编译。原因是:无法分配给 DateTime

which I cannot compile. Reason is : null cannot be assigned to DateTime.

因此,我必须声明一个 Nullable< DateTime>。 nullable 变量,并用 nullable 替换 null

So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

我不想使用 if 语句,而是想一行执行。

I do not want to use if-statement and I want to do this in one line.

此外,我可以在这里使用运算符 ??

Also, Can I use operator ?? here.

推荐答案

DateTime? dt = (string1 == string2) ? (DateTime?)null
                                    : DateTime.Parse(txtbox.Text);

这篇关于在三元运算中将null / Nullable分配给DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆