function | When writing a program, there will often be a constructor that provides a different scene for a type, perhaps most constructors are similar, and the default parameters are not allowed in C #, so the writing of the constructor is a repetitive task. But using copy and paste to complete the writing of constructors is sometimes difficult to achieve, especially when members are changed. Therefore, a more common substitution method is to provide a unified member function for the constructor to complete the initialization work.
For example:
public class MyClass
{
private int _age;
private string _name;
Public MyClass (String Name)
{
Initmember (Name, 20);
}
Public MyClass (String Name, int age)
{
Initmember (Name, age);
}
<summary>
Init Class Members
</summary>
<param name= "Name" ></param>
<param name= "Age" ></param>
private void Initmember (string Name, int age)
{
_age = age;
_name = Name;
}
}
However, a more concise approach in C # is to invoke another constructor in a constructor initialization statement, and the form above can be rewritten as follows.
public class MyClass
{
private int _age;
private string _name;
Public MyClass (string name): This (name, 20)
{}
Public MyClass (String Name, int age)
{
_age = age;
_name = Name;
}
}
For both, the execution efficiency is not much different, but the latter is much better in terms of code quality and makes the code look clearer.
Second, for the invocation of the base class. Because a member function cannot call the constructor of a base class, it is more difficult to write the first one, which is much simpler.
For example:
public class Myclass:baseclass
{
private int _age;
private string _name;
Public MyClass (string name): This (name, 20)
{}
Public MyClass (string name, int age): Base (name, age)
{
_age = age;
_name = Name;
}
}
One of the things to mention here is the constructor initialization statement, which can only be a single call to "this" or "base", and cannot coexist.
Finally, for the initialization of the ReadOnly constant, the ReadOnly constant cannot be modified in the member function because the ReadOnly constant can be modified only through the member initialization statement or in the constructor, which is also an important factor for constructor initialization statements to be better than member functions.
With the above note, for the comparison of the two, you can form the following simple comparison table.
|
Efficiency |
Code structure |
Base class Call |
Static member initialization |
Constructor Initialization statement |
The same |
Concise and clear |
Easy |
OK |
member functions |
More clear |
More Trouble |
No |
(Note: The Copy/paste method is not advocated here to repeat the constructor)