类的 多个构造函数 问题
class Class1 {
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
Class1() { }
Class1(int i1, int i2) {
i1 = i1;
i2 = i2;
}
Class1(int i1, int i2, int i3, int i4) {
i1 = i1;
i2 = i2;
i3 = i3;
i4 = i4;
}
Class1(int i1, int i2, int i3, int i4, int i5, int i6) {
i1 = i1;
i2 = i2;
i3 = i3;
i4 = i4;
i5 = i5;
i6 = i6;
}
}
我记得可以调用本身的构造函数来赋值.不用这么麻烦的额!!!
------解决方案--------------------class Class1 {
int i1;
int i2;
int i3;
int i4;
int i5;
int i6;
Class1() { }
Class1(int i1, int i2) {
i1 = i1;
i2 = i2;
}
Class1(int i1, int i2, int i3, int i4) : this(i1, i2){
i3 = i3;
i4 = i4;
}
Class1(int i1, int i2, int i3, int i4, int i5, int i6): this(i1,i2,i3,i4) {
i5 = i5;
i6 = i6;
}
}
------解决方案--------------------C#3.0可以通过自动属性(或一般的属性)来直接赋值这样
public class C{
public int I1{get;set;}
public int I2{get;set;}
}
public class App{
C c;
public void Set(){
this.c=new C{
I1=1,I2=2
};//这种方示可代替构造函数,这样就不必象你那写多个不同的构造函数版本了.例如下面这一行
是只初始化I1的情况;
//this.c=new C{I1=1};
}
}
这种方案,的执行发生在默认构造函数调用之后;以上那种方式是简写方式,完全写法如下
C# code
//...
public void Set(){
this.c=new C(){I1=1,I2=2};
}
//如果C中存在 public C(int i){this.I2=i;}那么也可以这样
public void Set(){
this.c=new C(22){I1=1,I2=2};
}
------解决方案--------------------
C# code
class Class1
{
private int i1;
private int i2;
private int i3;
private int i4;
private int i5;
private int i6;
public Class1() { }
public Class1(int i1, int i2)
{
this.i1 = i1;
this.i2 = i2;
}
public Class1(int i1, int i2, int i3, int i4)
: this(i1, i2)
{
this.i3 = i3;
this.i4 = i4;
}
public Class1(int i1, int i2, int i3, int i4, int i5, int i6)
: this(i1, i2, i3, i4)
{
this.i5 = i5;
this.i6 = i6;
}
}