为什么C#中的DateTime不允许为null? [英] Why is null not allowed for DateTime in C#?

查看:715
本文介绍了为什么C#中的DateTime不允许为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C#中不允许将null分配给DateTime?这是如何实施的?可以使用此功能使您自己的类不可为空吗?

示例:

string stringTest = null; // Okay
DateTime dateTimeTest = null; // Compile error

我知道我可以在C#2.0中使用DateTime?将null分配给dateTimeTest,并且可以使用解决方案

DateTime是值类型(struct),其中-string是引用类型(class等).那是关键的区别.引用始终可以为null;一个值不能(除非它使用Nullable<T>-即DateTime?),尽管它可以为零(DateTime.MinValue),通常将其解释为与null相同(尤其是1.1)./p>

Why it is not allowed to assign null to a DateTime in C#? How has this been implemented? And can this feature be used to make your own classes non-nullable?

Example:

string stringTest = null; // Okay
DateTime dateTimeTest = null; // Compile error

I know that I can use DateTime? in C# 2.0 to allow null to be assigned to dateTimeTest and that I could use Jon Skeet's NonNullable class on my string to get a run time error on the assignment of stringTest. I'm just wondering why the two types behave differently.

解决方案

DateTime is a value-type (struct), where-as string is a reference-type (class etc). That is the key difference. A reference can always be null; a value can't (unless it uses Nullable<T> - i.e. DateTime?), although it can be zero'd (DateTime.MinValue), which is often interpreted as the same thing as null (esp. in 1.1).

这篇关于为什么C#中的DateTime不允许为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆