gpt4 book ai didi

c# - 无法将类型 'System.DateTime?' 隐式转换为 'System.DateTime' 。存在显式转换(您是否缺少转换?)

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:23 25 4
gpt4 key购买 nike

我想我应该使用这样的东西,但我不确定如何修改它以使其适用于 DateTime,因为在这样做时它告诉我 DateTime 不能为 null。那么我该如何改变这个或者有更好的方法来解决这个问题呢?提前谢谢你。

我要设置什么

startDateTime = RadDateTimePickerBegin.SelectedDate;

我觉得应该是这样的

RadDateTimePickerBegin.SelectedDate == What goes here(string.Empty) ? (object)DBNull.Value : RadDateTimePickerBegin.SelectedDate);

最佳答案

看起来您正在使用 RadDateTimePicker 控件,在这种情况下 SelectedDate属性不是 DateTime值(value)。 It's a Nullable<DateTime> .这意味着您可能应该这样做:

 startDateTime = RadDateTimePickerBegin.SelectedDate ?? default(DateTime);

请注意:如果未选择任何日期,您最终会选择 0001 年 1 月 1 日作为日期,而不是您期望的 DBNull。

此外,我看到你转换到 Object在这里,这告诉我你可能会犯一个大错误。它看起来像 startDateTime将被分配给 SqlParameter 对象的值,为了使该变量能够同时保存 DateTime 和 DBNull 类型的项目,它必须具有 Object 类型.如果稍后使用 AddWithValue() 创建 SqlParameter方法,该方法可能不会正确猜测参数类型,因为它只会看到 Object。类型。发生这种情况时,您可能会受到严重的性能损失,因为类型不匹配会强制在数据库中进行每行转换或妨碍索引的良好使用。

如果您真的坚持当前的道路,您可以改为这样做:

 startDateTime = (RadDateTimePickerBegin.SelectedDate.HasValue)?
(Object)RadDateTimePickerBegin.SelectedDate.Value
:(Object)DBNull.Value;

但再次声明:我强烈建议不要这样做。

关于c# - 无法将类型 'System.DateTime?' 隐式转换为 'System.DateTime' 。存在显式转换(您是否缺少转换?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22331210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com