代码之家  ›  专栏  ›  技术社区  ›  Bastien Vandamme

为什么DateTime是.Net中的一种结构?

  •  13
  • Bastien Vandamme  · 技术社区  · 15 年前

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

    (我希望能够重写ToString()方法,但我不能。)

    8 回复  |  直到 15 年前
        1
  •  17
  •   Ruben    15 年前

    可能是因为它被看作是一个小的、简单的、不可变的数据结构,很像整数或小数。在这些条件下使其成为一个结构使使用DateTime非常有效。如果它是一个类,那么这种效率优势就会丢失,因为每次创建新的日期时间时都需要内存分配。

    此外,你能想出多少种不同的日期时间形式?(忽略您心目中的AllternateTostring实现)它并不是一种邀请多态性的类型。

    请注意,对于使用不同的DateTimes格式策略(我认为这是您想要的),您最好使用不同的格式设置方法,而不仅仅是使用ToString。如果你看 ICustomFormatter 接口,您将看到如何插入String.Format管道以覆盖格式化,而无需子集现有类型。

        2
  •  15
  •   Ralf de Kleine    10 年前

    声明扩展名:

    public static class DateTimeExtensions
    {
        public static string ToStringFormatted(this DateTime date)
        {
            return date.ToString("{d}");
        }
    }
    

    using DateTimeExtensions;
    ...
    var d = new DateTime();
    System.Diagnostics.Debug.WriteLine(d.ToStringFormatted());
    

    通过这种方式,您可以简单地实现自己在DateTime上使用的方法。这样,它可以轻松地在解决方案中的任何地方使用。唯一需要做的就是使用名称空间。

    裁判: Extension Methods (c#)

        3
  •  12
  •   Yuriy Faktorovich    15 年前

    因为它是一个单点。它没有多条数据。在引擎盖下,它由一个长的。

        4
  •  5
  •   Alexander Gräf    15 年前

    如果您想了解更多关于系统类和结构的信息,请下载免费的.NET reflector( http://www.red-gate.com/products/reflector/ ).

        5
  •  5
  •   Wayne Hartman    15 年前

    仅仅因为它是一个结构(或者即使它是一个密封的类),这并不意味着它是道路的尽头。你可以用电脑解决这个问题 composition ,而不是继承。下面是一个将DateTime类“对象化”的示例:

    public class MyDateTime
    {
        DateTime? value;
    
        public MyDateTime()
        {
            this.Value = DateTime.Now;
        }
    
        public MyDateTime(DateTime? dateTime)
        {
            this.Value = dateTime;
        }
    
        public override String ToString()
        {
            if (this.Value != null)
            {
                return this.Value.Value.Month.ToString() + " my favorite time of the year";
            }
    
            return null;
        }
    
        public System.DateTime? Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }
    
        6
  •  4
  •   Community CDub    8 年前

    我认为它是一个结构,因为结构是值类型,类是引用类型。DateTime中的实际数据是一个长整数。如果它是一个类,那么每次创建一个新对象时,堆上将分配8个字节,堆栈上将为指针分配另外8个字节。因此,通过使DateTime成为一个结构,它有效地将内存需求减少了一半。

    您可以在中找到更多信息 this question .

        7
  •  3
  •   elder_george    15 年前
    • 在赋值时复制它是合乎逻辑的,而不是创建对同一对象的引用,特别是因为它是不可变的。对它的操作也是如此( Add , Substract )

    如果您想要自定义格式,您可以像图中所示那样实现它 here

        8
  •  2
  •   Hannoun Yassir    10 年前

    你不需要越界 ToString() here 你不会真的需要其他人:)

    更详细的帖子 here