System.DateTime初始化为null的思维痕迹

本文探讨了在编程中如何正确初始化Nullable类型以避免null转换错误,通过实例展示了int、bool、double等类型的初始化方法,并解释了Nullable类型在解决null问题上的应用。
 DateTime dt = null;

如果我们这样写,生成时就会提示错误信息:

无法将Null转换成"System.DateTime",因为它是一种不可为null值的类型

 

之前也一直以为DateTime类型的对象无法初始化为空值null,刚在网上查了相关资料后找到了解决方法,现整理一下:

    DateTime? dt = null;   //初始化为null
    dt = System.DateTime.Now; 

 

没错,就加个问号一切问题都解决了,后来再查了下,是说

DateTime? 是 Nullable<DateTime> 的缩写,

如此一来呢,我们自然想试试平时不能初始化为null的其他类型是不是也可以这样赋为null,经验证int,bool,double等类型是可以的。

挺好玩的哈 :) 

C:\Program Files\nginx-1.22.1>nginx-service.exe install log4net:ERROR Exception while reading ConfigurationSettings. Check your .config file is well formed XML. System.TypeInitializationException: The type initializer for 'log4net.Util.Syste mInfo' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.DateT ime' threw an exception. ---> System.ArgumentNullException: Value cannot be null. (Parameter 'handle') at System.Runtime.InteropServices.NativeLibrary.GetExport(IntPtr , String ) at System.DateTime.GetGetSystemTimeAsFileTimeFnPtr() at System.DateTime..cctor() --- End of inner exception stack trace --- at System.DateTime.get_UtcNow() at log4net.Util.SystemInfo..cctor() --- End of inner exception stack trace --- at log4net.Util.SystemInfo.GetAppSetting(String key) at log4net.Util.LogLog..cctor() Unhandled exception. System.TypeInitializationException: The type initializer fo r 'WinSW.Program' threw an exception. ---> System.TypeInitializationException: The type initializer for 'log4net.Core .LoggerManager' threw an exception. ---> System.TypeInitializationException: The type initializer for 'log4net.Util .SystemInfo' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.DateT ime' threw an exception. ---> System.ArgumentNullException: Value cannot be null. (Parameter 'handle') at System.Runtime.InteropServices.NativeLibrary.GetExport(IntPtr , String ) at System.DateTime.GetGetSystemTimeAsFileTimeFnPtr() at System.DateTime..cctor() --- End of inner exception stack trace --- at System.DateTime.get_UtcNow() at log4net.Util.SystemInfo..cctor() --- End of inner exception stack trace --- at log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly) at log4net.Core.LoggerManager.GetVersionInfo() at log4net.Core.LoggerManager..cctor() --- End of inner exception stack trace --- at log4net.Core.LoggerManager.GetLogger(Ass
08-19
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值