Use the reflection to assign the default value of the C#attribute
In object -oriented programming, the attribute is often required to be initialized to the default value, especially during the process of serialization and desertification. Although the Switch statement can be used to set the default value according to the type, the more effective method is to use reflection, which provides a programming solution.
Solution
The default value of the attribute with reflection is assigned to the attribute. Two situations need to be considered: value type and reference type.
Value type
For value type (save actual data), you can use the method. This method creates a new example of specified value type, which effectively initializes it into the default value.
Quote type Activator.CreateInstance
<code class="language-csharp">object value = Activator.CreateInstance(type);</code>
Found implementation
A combination of value type and reference type method can define a generic method to provide a unified way to obtain the default value.
<code class="language-csharp">object reference = null;</code>
Note: In the newer .NET version (such as .NET Standard), should be written as
.The above is the detailed content of How Can Reflection Be Used to Assign Default Values to Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!