Re-using code when Constructor overloading?
本问题已经有最佳答案,请猛点这里访问。
所以一开始,我有下面的构造函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | public WaitPanelThread(Point origin, int delay, //bool westEast, String direction, Panel panel, Color colour, Semaphore semaphore, Semaphore semaphore2, Semaphore parkSemaphore, Semaphore nextSlot, Buffer buffer, Buffer buffer2, Buffer parkBuffer, String panelParkSpot, String nextSpot) { this.origin = origin; this.delay = delay; this.nextSpot = nextSpot; this.parkBuffer = parkBuffer; this.nextSlot = nextSlot; this.panelParkSpot = panelParkSpot; //this.westEast = westEast; this.direction = direction; this.parkSemaphore = parkSemaphore; this.panel = panel; this.colour = colour; this.plane = origin; if (direction =="down") { this.yDelta = 2; this.xDelta = 0; } if (direction =="left") { this.xDelta = -10; this.yDelta = 0; } if (direction =="right") { this.xDelta = 10; this.yDelta = 0; } this.panel.Paint += new PaintEventHandler(this.panel_Paint); //this.xDelta = westEast ? +10 : -10; //this.yDelta = 0; this.semaphore = semaphore; this.semaphore2 = semaphore2; this.buffer = buffer; this.buffer2 = buffer2; } |
然后我意识到,对于一些对象,我还需要三个参数。所以我用另外三个参数重载构造函数,复制粘贴代码并分配额外的参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | public WaitPanelThread(Point origin, int delay, //bool westEast, String direction, Panel panel, Color colour, Semaphore semaphore, Semaphore semaphore2, Semaphore parkSemaphore, Semaphore nextSlot, Buffer buffer, Buffer buffer2, Buffer parkBuffer, String panelParkSpot, String nextSpot, bool isTurn, Semaphore altSem, Buffer altBuf) { this.origin = origin; this.delay = delay; this.nextSpot = nextSpot; this.parkBuffer = parkBuffer; this.nextSlot = nextSlot; this.panelParkSpot = panelParkSpot; //this.westEast = westEast; this.direction = direction; this.parkSemaphore = parkSemaphore; this.isTurn = isTurn; this.panel = panel; this.colour = colour; this.plane = origin; this.altSem = altSem; this.altBuf = altBuf; if (direction =="down") { this.yDelta = 2; this.xDelta = 0; } if (direction =="left") { this.xDelta = -10; this.yDelta = 0; } if (direction =="right") { this.xDelta = 10; this.yDelta = 0; } this.panel.Paint += new PaintEventHandler(this.panel_Paint); //this.xDelta = westEast ? +10 : -10; //this.yDelta = 0; this.semaphore = semaphore; this.semaphore2 = semaphore2; this.buffer = buffer; this.buffer2 = buffer2; } |
因此,正如您所看到的,这两个构造函数在其实现中基本上是相同的,除了三个额外的参数(一个布尔值、一个信号量和一个缓冲区)。我想知道的是,不是在重载的构造函数中编写所有的代码,而是有一种引用第一个构造函数的方法,并且只需要为extr编写额外的代码一个参数?
我说的是在继承类中使用"super()"方法(我研究过它,这里无法完成,因为它们在同一个类中)。
谢谢您。
其语法是(在构造函数中):
1 2 3 4 | public WaitPanelThread( ... parameters...) : this(..parameters for another constructor..) { // initialize the optional parameters here } |