将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之类的值作为默认值。
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?
。