为什么DateTime是.Net中的一个结构? [英] Why is DateTime a structure in .Net?

查看:256
本文介绍了为什么DateTime是.Net中的一个结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 DateTime 一个结构而不是可继承的类?

Why is DateTime a structure instead of an inheritable class?

(我想要能够覆盖ToString()方法,但我不能。)

(I would like to be able to override the ToString() method but I can't.)

推荐答案

可能是因为它被看作是一个小而简单和不可变的数据结构,很像一个整数或十进制。在这些条件下使其成为一个结构体,使得使用DateTime非常有效。如果它已经成为一个类,那么这个效率的好处就会丢失,因为每次创建一个新的DateTime都需要内存分配。

Probably because it was seen as a small, simple and immutable data structure, much like an integer or decimal. Making it a struct under these conditions make using a DateTime very efficient. If it had been made a class, this efficiency benefit would have been lost because that would require memory allocations every time you create a new DateTime.

此外,您可以提出一个DateTime的变体形式有多少? (忽略了您所想到的全面ToString实现)。它不是一种引用多态的类型。

Besides, how many variant forms of a DateTime can you come up with? (Ignoring the allternate ToString implementations you have in mind.) It's not exactly a type that invites polymorphism.

请注意,对于您的DateTimes使用不同的格式策略,因为我想想你想要的,最好是用不同的方式来格式化,而不是使用ToString。如果您查看MSDN中的 ICustomFormatter 界面,那么您将看看如何插入String.Format管道来覆盖格式,而不需要对现有类型进行子集。

Note that for using a different formatting strategy for your DateTimes, as I think you want, you'd better look at a different way to format than just using ToString. If you look at the ICustomFormatter interface in MSDN, you'll see how you can plug into the String.Format pipeline to override formatting without needing to subset an existing type.

这篇关于为什么DateTime是.Net中的一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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