Set a default value to a property

后端 未结 5 1570
你的背包
你的背包 2021-02-11 21:58

Is it possible to set a default value without the body of a property? Preferably with annotations.

[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }
         


        
5条回答
  •  伪装坚强ぢ
    2021-02-11 22:41

    No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted to the constructor) to set the default values.

    If you have several overloads for your constructor, you may want to look at constructor chaining.

    Using C# 6+, you are able to do something like this...

    public string MyValue { get; set; } = "My Default";
    

    Oh, it gets more fun because people have even requested something like this...

    // this code won't compile!
    public string MyValue {
        private string _myValue;
        get { return _myValue ?? "My Default"; }
        set { _myValue = value; }
    }
    

    ... the advantage being that you could control the scope of the field to only be accesible in the property code so you don't have to worry about anything else in your class playing with the state without using the getter/setter.

提交回复
热议问题