default value for a static property

前端 未结 4 1858
情书的邮戳
情书的邮戳 2021-01-03 17:41

I like c#, but why can I do :

public static bool Initialized { private set; get; }

or this :

public static bool Initialized         


        
4条回答
  •  情话喂你
    2021-01-03 18:15

    The two blocks of code you have mentioned are two different things.

    The first block is an auto implemented property defination. This is syntactic sugar for a full property defination which looks like this:

    private static bool _initialized;
    public static bool Initialized
    {
        private set
        {
            _initialized = value;
        }
        get
        {
            return _initialized;
        }
    }
    

    Your second block of code is a static member definition. If you look at the expansion I have given above, you'll notice that it includes a private static member definition. If you want to provide an initial value you can do it here:

    private static bool _initialized = false;
    public static bool Initialized
    {
        private set
        {
            _initialized = value;
        }
        get
        {
            return _initialized;
        }
    }
    

    The inline property definition you are using was designed just to make code a bit shorter in the most common case. If you want to do anything else, you can use the full form of the property code.

    Alternatively, you can go down a completely different route and use a static constructor. (See Corey's answer)

提交回复
热议问题