int a, b, c;
Constructor()
{
a = 5;
b = 10;
c = 15;
//do stuff
}
Constructor(int x, int y)
{
a = x;
b = y;
c = 15;
//do stuff
}
Constructor(int x, int y, int z)
{
a = x;
b = y;
c = z;
//do stuff
}
为了避免“东西”的重复和减少一些赋值操作,我尝试了以下方法:
int a, b, c;
Constructor(): this(5, 10, 15)
{
}
Constructor(int x, int y): this(x, y, 15)
{
}
Constructor(int x, int y, int z)
{
a = x;
b = y;
c = z;
//do stuff
}
这个对我想做的事情有用,但有时我需要使用一些冗长的代码来创建新对象或进行一些计算:
int a, b, c;
Constructor(): this(new Something(new AnotherThing(param1, param2, param3),
10, 15).CollectionOfStuff.Count, new SomethingElse("some string", "another
string").GetValue(), (int)Math.Floor(533 / 39.384))
{
}
Constructor(int x, int y): this(x, y, (int)Math.Floor(533 / 39.384))
{
}
Constructor(int x, int y, int z)
{
a = x;
b = y;
c = z;
//do stuff
}
这段代码与之前几乎相同,只是传递的参数不太易读。我更喜欢做这样的事情:
int a, b, c;
Constructor(): this(x, y, z) //compile error, variables do not exist in context
{
AnotherThing at = new AnotherThing(param1, param2, param3);
Something st = new Something(aThing, 10, 15)
SomethingElse ste = new SomethingElse("some string", "another string");
int x = thing.CollectionOfStuff.Count;
int y = ste.GetValue();
int z = (int)Math.Floor(533 / 39.384);
//In Java, I think you can call this(x, y, z) at this point.
this(x, y, z); //compile error, method name expected
}
Constructor(int x, int y): this(x, y, z) //compile error
{
int z = (int)Math.Floor(533 / 39.384);
}
Constructor(int x, int y, int z)
{
a = x;
b = y;
c = z;
//do stuff
}
基本上我正在构建构造函数内的参数。然后我尝试将这些构建好的参数传递给另一个构造函数。我记得在Java中编码时,可以使用"this"和"super"关键字在另一个构造函数体内调用构造函数。但是在C#中似乎不可能。有没有一种简单的方法可以做到这点?我做错了什么吗?如果不可能的话,我应该坚持难以阅读的代码吗?
我想我可以将重复的代码剪切成完全位于构造函数之外的另一个方法。然后每个构造函数只需要执行自己的操作并调用其他构造函数共享的代码。