简体   繁体   中英

why do we define a struct object from itself in the struct definition

in the code below, there is a struct defined. In the definition there are some structs created from itself. it comes to me like a mirror in the mirror, or calling a recursive function a recursive function. Because you are defining some variable while variable is still not defined, i mean in itself?? How does it work? why do we use it in general? and what is the effect?

thanks for explanation..

public struct **PersonId**
{
    public static readonly **PersonId** default= new PersonId(value,1,1);
    public static readonly **PersonId** x = new PersonId(someValue, 0, 0);
    public static readonly **PersonId** y = new PersonId(someOtherVale,-1,0);

    [DataMember]
    public int Prop1 { get; private set; }
    [DataMember]
    public int Prop2 { get; private set; }
    [DataMember]
    public int Prop3 { get; private set; }

    public PersonId(int prop1 , int prop2 , int prop3 )
        : this()
    {
        Prop1 = prop1 ;
        Prop2 = prop2 ;
        Prop3 = prop3 ;
    }

Think of a static as a global variable - you are effectively declaring default and x and y as global variables (*).

If you couldn't do this, how would you expect something like DateTime.MinValue to work?

public static readonly DateTime MinValue = new DateTime(0L, DateTimeKind.Unspecified);

Note that your code won't compile if you removed the static as discussed at https://stackoverflow.com/a/8892920/34092 .

(*) Not strictly speaking true, but stick with me for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM