将DateTime设置为空值c#

将DateTime设置为空值c#,c#,datetime,nullable,C#,Datetime,Nullable,我正在尝试在我的应用程序中将日期时间设置为空值-我正在以以下方式尝试 string datetime = Convert.ToString(dataRow["dbfield"]).Trim(); MyDateTime= string.IsNullOrEmpty(datetime) ? (DateTime?) null : GeneralUtilities.ConvertOTDateToDate(dat

我正在尝试在我的应用程序中将日期时间设置为空值-我正在以以下方式尝试

    string datetime = Convert.ToString(dataRow["dbfield"]).Trim();
    MyDateTime= string.IsNullOrEmpty(datetime)
                    ? (DateTime?) null
                    : GeneralUtilities.ConvertOTDateToDate(datetime);
我得到的错误是

无法隐式转换类型System.Datetime?到System.Datetime,一个 存在显式转换。是否缺少强制转换

请有人能帮我正确的语法吗


谢谢

我假设
MyDateTime
被声明为
DateTime
。将其更改为
DateTime?

GeneralUtilities.ConvertOTDateToDate
返回一个
DateTime
。将其转换为
DateTime?
。例如:

MyDateTime= string.IsNullOrEmpty(datetime)
                ? (DateTime?) null
                : (DateTime?)GeneralUtilities.ConvertOTDateToDate(datetime);

我假设
MyDateTime
被声明为
DateTime
。将其更改为
DateTime?

GeneralUtilities.ConvertOTDateToDate
返回一个
DateTime
。将其转换为
DateTime?
。例如:

MyDateTime= string.IsNullOrEmpty(datetime)
                ? (DateTime?) null
                : (DateTime?)GeneralUtilities.ConvertOTDateToDate(datetime);

DateTime是一个结构,因此不能为null。把它改成日期时间?如果要使用null。或者使用DateTime.MinValue之类的内容作为默认值。

DateTime是一个结构,因此不能为null。把它改成日期时间?如果要使用null。或者使用DateTime.MinValue之类的值作为默认值。

,他回来了两个不同的地方values@wudzik不,它肯定是第一个,因为您可以隐式地将
DateTime
转换为
DateTime?
@cfrozendath:是的,但这与OPs问题无关@juharr,很难判断它是哪个,因为没有提供
MyDateTime
的声明,也没有
GeneralUtilities的方法签名。ConvertOTDateToDate
@Amy,消息是关于将
DateTime?
转换为
DateTime
。三元运算符的结果将是一个
DateTime?
,因为无论方法返回什么,强制转换都是如此。因此,变量是
DateTime
@cfrozendath。只有当方法返回
DateTime?
时,强制转换才是冗余的。如果它返回
DateTime
,则强制转换将三元返回设置为
DateTime?
。第二个是真的,他回来了两个不同的地方values@wudzik不,它肯定是第一个,因为您可以隐式地将
DateTime
转换为
DateTime?
@cfrozendath:是的,但这与OPs问题无关@juharr,很难判断它是哪个,因为没有提供
MyDateTime
的声明,也没有
GeneralUtilities的方法签名。ConvertOTDateToDate
@Amy,消息是关于将
DateTime?
转换为
DateTime
。三元运算符的结果将是一个
DateTime?
,因为无论方法返回什么,强制转换都是如此。因此,变量是
DateTime
@cfrozendath。只有当方法返回
DateTime?
时,强制转换才是冗余的。如果它返回
DateTime
,则强制转换将三元返回设置为
DateTime?