Set a default value to a property

后端 未结 5 1602
你的背包
你的背包 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:39

    Assign the default property value in the class constructor.

    class MyClass
    {
        public MyClass()
        {
            IsTrue = true;
            IsFalse = false;
        }
    
        public bool IsTrue { get; set; }
    
        public bool IsFalse { get; set; }
    
        [...]
    
        public void Something()
        {
            var isTrue = this.IsTrue;
            var isFalse = this.IsFalse;
        }
    }
    

提交回复
热议问题