The initial value assignment method of the automatic attribute of the automatic attribute
C #'s automatic attribute provides a simple syntax to define the attributes with automatic Getter and Setter. However, the assignment of automatic attributes needs to be traditionally used to use a constructor or restore the old attribute grammar.
Traditional methods
Construct function initialization:
Initialize automatic properties in the constructor to ensure that it is valuable when the object is created.<code class="language-csharp">class Person { public Person() { Name = "初始名称"; } public string Name { get; set; } }</code>
<code class="language-csharp">private string name = "初始名称"; public string Name { get { return name; } set { name = value; } }</code>
DefaultValueAttribute is mainly used for Visual Studio designer to specify the default value displayed in the IDE. It does not affect the generated IL, nor is it used to initialize the attribute during runtime.
<code class="language-csharp">public int X { get; set; } = x; // C# 6 或更高版本</code>
The above is the detailed content of How Can I Assign Initial Values to C# Auto-Properties?. For more information, please follow other related articles on the PHP Chinese website!