maj*_*k86 2 c# initialization class
得到了这个有很多属性的类.有一个构造函数,它将属性设置为默认值和Clear方法.(这里的清除方法只是一个例子)
public class Person
{
public string A;
public string B;
public string C;
...
public string Z;
public Person()
{
this.A = "Default value for A";
this.B = "Default value for B";
this.C = "Default value for C";
...
this.Z = "Default value for Z";
}
public void Clear()
{
this = new Person(); // Something like this ???
}
}
Run Code Online (Sandbox Code Playgroud)
如何通过Clear方法重新初始化课程?
我的意思是:
Person p = new Person();
p.A = "Smething goes here for A";
p.B = "Smething goes here for B";
...
// Here do stuff with p
...
p.Clear(); // Here I would like to reinitialize p through the Clear() instead of use p = new Person();
Run Code Online (Sandbox Code Playgroud)
我知道我可以编写一个包含所有默认值设置的函数,并在构造函数和Clear方法中使用它.但是......有一种"正确"的方式而不是解决方法吗?
我宁愿实施initializer:
public class Person
{
public string A;
public string B;
public string C;
...
public string Z;
private void Ininialize() {
this.A = "Default value for A";
this.B = "Default value for B";
this.C = "Default value for C";
...
this.Z = "Default value for Z";
}
public Person()
{
Ininialize();
}
public void Clear()
{
Ininialize();
}
}
Run Code Online (Sandbox Code Playgroud)
....
Person p = new Person();
...
p.A = "Something goes here for A";
p.B = "Something goes here for B";
...
p.Clear(); // <- return A, B..Z properties to their default values
Run Code Online (Sandbox Code Playgroud)