更好的DateTime?或使用默认值(日期时间)为NULL? [英] Better DateTime? or use default(DateTime) for NULL?

查看:739
本文介绍了更好的DateTime?或使用默认值(日期时间)为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计一个C#/ NHibernate的网站,设有一个私人邮件系统。我想管理员检查,如果当一个消息已被用户阅读,同时强调,还没有被用户读取但这些消息。为了实现这两个,我发现了两个选项:

I'm designing a C#/NHibernate website that features a private messaging system. I would like admins to check if and when a message has been read by a user, and together highlight those messages that haven't been read yet by users. To achieve both, I found two options:

选项1

class Message
{
    DateTime? Read;
}



其中,阅读== NULL 表示不读尚未

选项2

class Message
{
    DateTime Read;
}



其中,阅读==默认设置(日期时间)(1月1日公元1 0:00:00)指不读呢。

where Read==default(DateTime) (January 1st 1 A.D., 0:00:00) means not read yet.

在大学里,我一直在教导使用 NULL 值来处理所有的特殊的情况下,也使用可空类型的看起来的一个很好的选择,因为它的看起来更容易的通过检查他们是否 NULL 或不会查询未读邮件。

At university, I have been taught to use the NULL value to handle all special cases, and also using the nullable type seems a good choice since it looks easier to query for unread messages by checking whether they are NULL or not.

不过,使用可空类型至少涉及到装箱和拆箱的代码,具有性能下降。在另一方面,在查询未读邮件意味着在比较值(但它可以被索引)

But, using nullable types at least involves boxing and unboxing in code, with performance decreasing. On the other hand, querying for unread messages means comparing the value (but it can be indexed)

你有什么建议的方法为这个?将最佳实践在这种情况下,有什么建议?

What is your suggested approach for this? What would best practices suggest in this case?

推荐答案

使用的DateTime? 。其具体目的是为了避免使用保留值(又名幻数)为代表的特殊情况下,如

Use DateTime?. Its specific purpose is to avoid using reserved values (aka "magic numbers") to represent special cases, such as null.

此外,如果使用可空类型没有引入拳击本身。将已经装箱依然任何值会,但你不会切换简单地引入任何拳击。在可空< T> 类型实际上是一个结构,并与来比较的能力(或没有在VB.NET)是严格意义上的语言习惯。在内部,它被翻译成关于的HasValue 属性检查。

Also, using a nullable type introduces no boxing itself. Any values that would have been boxed still will be, but you won't introduce any boxing simply by switching. The Nullable<T> type is actually a struct, and the ability to compare with null (or Nothing in VB.NET) is strictly a language convention. Under the covers, it gets translated into a check on the HasValue property.

这篇关于更好的DateTime?或使用默认值(日期时间)为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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