【发布时间】:2015-11-12 09:24:02
【问题描述】:
外部框架具有以下类:
public class Boatmaker
{
}
public class Wood
{
}
public class Axe
{
}
public class Lake
{
}
public class Boat
{
public Boat(Wood wood, Axe axe) {
}
public Boat (Boatmaker maker) {
}
public Boat (Lake lake) {}
}
我需要做很多 Boat 的子类化。对于我的每个子类,我必须假设外部框架可能希望通过上述任何构造函数来实例化它。所以我的子类得到了传递构造函数。注意它们是如何永不消失的:
public class SmallBoat: Boat
{
public void DoSmallBoatStuff() {
// some code here
}
private void Initialize() {
this.DoSmallBoatStuff();
}
public SmallBoat(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public SmallBoat (Boatmaker maker): base(maker) {
this.Initialize();
}
public SmallBoat (Lake lake): base(lake) {
this.Initialize();
}
}
public class Canoe: SmallBoat
{
public void DoCanoeStuff() {
// some code here
}
private void Initialize() {
this.DoCanoeStuff();
}
public Canoe(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public Canoe (Boatmaker maker): base(maker) {
this.Initialize();
}
public Canoe(Lake lake): base(lake) {
this.Initialize();
}
}
我想知道是否有办法简化代码的外观。 SmallBoat 和 Canoe 中构造函数的编写方式之间的唯一区别是 SmallBoat 或 Canoe 这个词。其他一切都一样。
因此,如果有一种方法可以在不实际使用构造函数中的类名的情况下编写构造函数,那将有很大帮助。我可以在没有 .tt 文件的情况下使用直接复制和粘贴(这对我来说并不可行——我的大部分工作都没有在 Visual Studio 中完成)。有没有办法做到这一点?
【问题讨论】:
标签: c# inheritance constructor