获得了具有许多属性的此类。有构造函数将属性设置为其默认值和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 ???
}
}
我如何通过清除方法重新初始化类?
我的意思是:
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();
我知道我可以写一个函数的所有默认值设置,并在构造函数和清除方法使用它。但是......有没有一种“适当”的方式而不是解决方法?
你有什么具体的原因,为什么你想重用的实例? – jnovacho
避免内存分配我猜:这是一个相当高尚的目的:) – Kek