[英]Nullable datetime value from DatePicker
This is the case. 情况就是这样。 I get the date from DatePicker control: 我从DatePicker控件获取日期:
DateTime current = datePicker1.SelectedDate; DateTime current = datePicker1.SelectedDate;
And I get an error: Cannot implicitly convert DateTime? 我收到一个错误:无法隐式转换DateTime? to DateTime. 到DateTime。 So I guess it's up to a nullable type DateTime?. 所以我想这是一个可以为空的类型DateTime?
Is it safe to cast this type to a type I need like this: 将此类型转换为我需要的类型是否安全:
if (datePicker1.SelectedDate == null)
current= DateTime.Now;
else
current= (DateTime)datePicker1.SelectedDate; //or datePicker1.SelectedDate.Value
And in general, when is it SAFE to implicitly cast nullable values, and when it isn't? 一般来说,什么时候隐式地施放可以为空的值是安全的,什么时候不是?
In this case you should use the null coalescing operator : 在这种情况下,您应该使用null合并运算符 :
current = datePicker1.SelectedDate ?? DateTime.Now;
That will use SelectedDate
if it's non-null, or DateTime.Now
otherwise. 如果它是非null,那将使用SelectedDate
,否则使用DateTime.Now
。 The type of the expression is non-nullable, because the last operand is. 表达式的类型是不可为空的,因为最后一个操作数是。
In general, you should use the Value
property (or cast to the non-nullable type) if you're confident that the value is non-null at that point - so that if it is null, it will throw an exception. 通常,如果您确信该值在该点处为非null,则应使用Value
属性(或强制转换为非可空类型) - 因此,如果它为 null,则会抛出异常。 (If you're confidence is misplaced, an exception is appropriate.) Quite often the null coalescing operator means you don't need to worry about this though. (如果你的信心是错误的,那么一个例外是合适的。)通常,空合并运算符意味着你不需要担心这一点。
Nullable types have a special property for this kind of thinks. 可空类型具有这种思想的特殊属性。 It is HasValue, and moreover GetValueOrDefault. 它是HasValue,而且还有GetValueOrDefault。 So what You really need is 所以你真正需要的是
DateTimePicker1.SelectedDate.GetValueOrDefault(DateTime.Now);
// or DateTime.MaxValue or whatever)
. // or DateTime.MaxValue or whatever)
。
You don't need to cast, the following 你不需要施放,以下内容
if (datePicker1.SelectedDate == null)
current= DateTime.Now;
else
current= datePicker1.SelectedDate.Value;
should do 应该做
How about 怎么样
DateTime current = datePicker1.SelectedDate ?? DateTime.Now;
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.