Reconciling properties of structs and DateTime

后端 未结 2 897
一整个雨季
一整个雨季 2021-01-22 17:17

I have been looking through the DateTime structure and I am slightly confused.

My understanding with structs is that you cannot assign \'default values\' of fields. If t

相关标签:
2条回答
  • 2021-01-22 17:52

    Jon Skeet is right it's all about the difference between fields and other members. One could really make a "date time" like this:

    struct MyDateTime
    {
      // This is the only instance field of my struct
      // Ticks gives the number of small time units since January 1, 0001, so if Ticks is 0UL, the date will be just that
      readonly ulong Ticks;
    
      // here goes a lot of instance constructors,
      // get-only instance properties to show (components of) the DateTime in a nice way,
      // static helper methods,
      // and lots of other stuff, but no more instance fields
      ...
    }
    

    So in reality, MyDateTime is just a wrapped ulong with an interpretation, and a lot of nice ways to show and manipulate that ulong.

    0 讨论(0)
  • 2021-01-22 18:04

    You need to understand the difference between fields and properties.

    The fields are all initialized to 0, but the properties can do what they like with those fields. Sample:

    public struct Foo
    {
        private readonly int value;
    
        public Foo(int value)
        {
            this.value = value;
        }
    
        public int ValuePlusOne { get { return value + 1; } }
    }
    
    ...
    
    Foo foo = new Foo(); // Look ma, no value! (Defaults to 0)
    int x = foo.ValuePlusOne; // x is now 1
    

    Now obviously DateTime is a smidge more complicated than this, but it gives the right idea :) Imagine what "A DateTime with the field explicitly set to 0" would mean... the "default" DateTime just means exactly the same thing.

    0 讨论(0)
提交回复
热议问题