问题
I have a statement like
DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);
which I cannot compile. Reason is : null cannot be assigned to DateTime.
So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.
I do not want to use if-statement and I want to do this in one line.
Also, Can I use operator ?? here.
回答1:
DateTime? dt = (string1 == string2) ? (DateTime?)null
: DateTime.Parse(txtbox.Text);
回答2:
you can do it like that:
DateTime ? dt = (string1 == string2) ? new Nullable <DateTime>(): (DateTime)(txtbox.Text);
来源:https://stackoverflow.com/questions/6215199/assigning-null-nullable-to-datetime-in-ternary-operation