Default value for public properties

前端 未结 2 2042
别跟我提以往
别跟我提以往 2021-01-23 11:41

I have a public property in some class. I want a default value -1 for this property without an private variable like _MyField(because too many properties in this class, i won\'t

相关标签:
2条回答
  • 2021-01-23 12:27

    You basically have two options - you can set the property in the constructor of the object, or use a private field.

    Personally, I feel the constructor is the best option, as it's clear to people reading your code what your intentions are for a fresh instance of your class.

    [DefaultValue] is an attribute meant for use with visual designer functionality, and has no effect on your class logic.

    0 讨论(0)
  • 2021-01-23 12:34

    Just set a this.MyAttr = -1 assignment in the object's constructor.

    0 讨论(0)
提交回复
热议问题