c# – null和datetime之间没有隐式转换

栏目: C# · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/20398773/there-is-no-implicit-conversion-between-null-and-datetime

参见英文答案 > Conditional operator assignment with Nullable<value> types? 5个

下面的代码从给定的DataRow(modelValue)读取一个数据,并将其解析为可以为空的DateTime实例.

问题:请参阅L1&中的代码部分. L2两者在技术上相等(如果我没有造成任何小学生错误).但是,L1按预期工作,但不是L2.我正进入(状态

there is no implicit conversion between null and datetime

当我在L2下执行代码时.有人可以告诉我吗?

DateTime? CallBack;

        var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString();
        //Parsing
        DateTime cdate;
        if (!DateTime.TryParse(callBackDate, out cdate))
            cdate = DateTime.MinValue;


        //L1
        if (cdate==DateTime.MinValue)
            CallBack = null;
        else
           CallBack = cdate.Date;

       //L2  
       CallBack = cdate == DateTime.MinValue?null:cdate.Date;
(Z) ? X : Y

三元运算符要求从第二个操作数(X)到第三个操作数(Y)或从Y到X存在隐式转换.

由于null不能隐式转换为DateTime,也不能将DateTime转换为null,因此无法计算表达式.更多相关信息: Type inference woes by Eric Lippert .

你必须将null转换为DateTime?.通过这样做,X将是DateTime类型?和Y将是DateTime类型.由于存在从DateTime到DateTime?的隐式转换,因此可以计算表达式,并且它将返回DateTime?类型的值.

或者,按照相同的逻辑,您也可以将第三个操作数Y转换为DateTime?.

翻译自:https://stackoverflow.com/questions/20398773/there-is-no-implicit-conversion-between-null-and-datetime


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Delivering Happiness

Delivering Happiness

Tony Hsieh / Grand Central Publishing / 2010-6-7 / USD 27.00

http://www.deliveringhappinessbook.com/ The visionary CEO of Zappos explains how an emphasis on corporate culture can lead to unprecedented success. Pay new employees $2000 to quit. Make custome......一起来看看 《Delivering Happiness》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具