2014-02-27 48 views
2

获得了具有许多属性的此类。有构造函数将属性设置为其默认值和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(); 

我知道我可以写一个函数的所有默认值设置,并在构造函数和清除方法使用它。但是......有没有一种“适当”的方式而不是解决方法?

+1

你有什么具体的原因,为什么你想重用的实例? – jnovacho

+0

避免内存分配我猜:这是一个相当高尚的目的:) – Kek

回答

5

我宁愿落实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(); 
    } 
} 

....

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 
+0

是......或者把代码初始化成Clear方法并直接调用从构造函数中清除:你会避免一个函数(这不是什么大问题,我同意) – Kek

+0

@Kek:我宁愿分开Initialize()和Clear():通常你必须在Clear()上做一些额外的事情:例如请求许可,调用事件,说“清除”和“清除”等。 –

+0

@Dmitry感谢您的帮助。基本上,如果我将Initialize重命名为** SomethingElse **,那么它就是我刚才所说的:)我可以编写函数并在构造函数和Clear方法中使用它。如果有“预定的方式”,我只是**好奇**;像**这**参数左右.. – majk86

1

我不知道你想要什么,但我会做这样的:

public class Person 
{ 
    public string A; 
    public string B; 
    public string C; 
    ... 
    public string Z; 

    public Person() 
    { 
     ResetToDefault(); 
    } 

    public void ResetToDefault() 
    { 
     this.A = "Default value for A"; 
     this.B = "Default value for B"; 
     this.C = "Default value for C"; 
     ... 
     this.Z = "Default value for Z"; 
    } 
} 

好吧,在某些时候,你必须给参数的值。

当你想重置为默认..只是这样做:

Person person = new Person(); 
//do your stuff here ..... 
//when reset it: 
person.ResetToDefault(); 
+0

基本上和德米特里一样写道..但是谢谢:) – majk86

+0

欢迎光临:) – user1967122