开发者

C#: if a class has two constructors, what is the best way for these constructors to share some code? [duplicate]

This question already has answers here: Call one constructor from another (13 answers) 开发者_如何学JAVA Closed 9 years ago.

C# in VS2005: if a class has two constructors, what is the best way for these constructors to share some code?

eg. How could I avoid having the x = 5 and y = 10 lines in both constructors for the following:

public class MyObject {

int x;
int y;
int z;

public MyObject() {
    x = 5;
    y = 10;
}

public MyObject(int setZ) {
    x = 5;
    y = 10;
    z = setZ;
}


Just chain to the common constructor...

public MyObject(int setZ)
  : this()
{
  z = setZ;
}


Use the this() syntax.

public MyObject(int setZ) : this() {
    z = setZ;
}


Create another method:

private setDefaultNumbers() {
    x = 5;
    y = 10;
}

Then have both versions of your constructor call this method:

public MyObject() {
    setDefaultNumbers();
}

public MyObject(int setZ) {
    setDefaultNumbers();
    z = setZ;
}


It's very similar to the way you'd do it with methods. Normally you would do something like:

public void SetA(int a)
{
    this.a = a;
}

public void SetAandB(int a, int b)
{
    this.SetA(a);
    this.b = b;
}

with constructors, there's special syntax for it:

public void MyObject()
{
    this.a = 5;
}

public void MyObject(int b)
    : this()
{
    this.b = 10;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜