【发布时间】:2016-01-31 21:16:18
【问题描述】:
我需要如何重构或重构我的代码,以便我可以使用嵌入和继承的对象以最少的代码重复来按预期工作。 这段代码只是一个例子,我认为这是我的 OOP 思维中的一个基本错误......
该示例与 Car、Engine 和 Driver 等书籍中几乎所有常见的基类相同: 当我添加从基类继承的特殊类(如 Racecar:Car 和 TurboEngine:Engine)并将属性添加到特定类(如对 TurboEngine 的 boost)时,当我想使用与基类一样多的代码和方法时,我会遇到同样的问题类而不覆盖几乎所有方法。
我已经将我的字段重构为属性并尝试使用new 和override,但逻辑问题保持不变。
如果该代码太多,我可以尝试将其缩短为我遇到的单个问题。
示例代码显示了问题。上/下铸造无济于事。我想这更像是一个基本的思维错误,因为 OOP 编程对于一个老汇编程序来说很难学习。
编辑----更新:
好的,这是设计使然。 https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) https://en.wikipedia.org/wiki/Liskov_substitution_principle
我现在感觉有点松懈……卡在那里想:不可能是真的。 应该有更多地方可以指出、收集和展示这些常见错误,具体取决于开发人员的经验水平。同样在许多书中,它也远没有被强调。现在知道了它的正确术语,我发现了更多。但是还是有很多深入的技术讲解不适合新手。这样可以节省很多时间:)
var root = new Vector2D(0,0);
GameField2D fGame = new GameField2D(10,10);
fGame.Init();
fGame.Field[1,1].ParentPoint = root;
fGame.Field[1,1].Color = 1; //<--ERROR to be expected
var test = (TetrisField2D)fGame; //<---ERROR cast not possible
TetrisField2D fTetris = new TetrisField2D(10,10);
fTetris.Init();
fTetris.Field[1,1].ParentPoint = root; //<--ERROR Nullreference because only base class field is initiated.
以下是课程:
继承者:
public class TetrisField2D: GameField2D {
public int Lifes;
public TetrisPoint[,] Field; //I want of course Tetrispoints with color
public TetrisField2D(): base(){}
public TetrisField2D(int x,int y) : base (x,y) {}
}
基类
public class GameField2D { //"generic"
public GamePoint[,] Field;
private int size;
//CTORs
public GameField2D(){
Field = new GamePoint[9,9];
size = 10;
}
public GameField2D(int x,int y){
Field = new GamePoint[x-1,y-1];
size= x-1;
}
public GameField2D(GamePoint[,] f){
Field = f;
size = f.GetLength(0);
}
public void Init() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Field[i,j] = new GamePoint();
}
}
}
}
包含点类:
public class TetrisPoint : GamePoint{
public int Color;
public TetrisPoint(){}
public TetrisPoint(int x, int y, int col) : base(x,y) {
Color = col;
}
}
public class GamePoint {
public Vector2D ParentPoint;
public bool Appears;
public int IsUsed;
public GamePoint(){ }
public GamePoint(int x, int y, bool a=false) {
this.ParentPoint = new Vector2D(x,y);
Appears = a;
}
}
public struct Vector2D {
public int X,Y;
public Vector2D(int x,int y) {
this.X=x;
this.Y=y;
}
}
【问题讨论】:
标签: c# inheritance casting polymorphism