Reconciling properties of structs and DateTime

后端 未结 2 896
一整个雨季
一整个雨季 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 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.

提交回复
热议问题