通过其方法初始化类的新实例

时间:2014-02-27 11:13:09

标签: c# class initialization

这个类有很多属性。有一个构造函数,它将属性设置为默认值和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 ???
    }
}

如何通过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();

我知道我可以编写一个包含所有默认值设置的函数,并在构造函数和Clear方法中使用它。但是......有一种“正确”的方式而不是解决方法吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();