从函数抽象类,学习面向对象



论坛新手,我一直坚持从一个非常基本的函数创建一个抽象类的逻辑。我知道继承和重写是如何处理抽象类的,但我不知道将此函数转换为抽象类背后的逻辑。如有任何帮助,我们将不胜感激。

除此之外,我这样做是为了帮助我了解基本原理,并了解我应该采用的其他选择或良好做法。再次感谢您的帮助。

代码:

private readonly List<Shape> Square1 = new List<Shape>();
private void GenerateSquare()
{
Shape newSquare = RandomSquareLocation();
while (Square1.Any(square => square.X == newSquare.X && square.Y == newSquare.Y))
{
newSquare = RandomSquareLocation();
}
Square1.Add(newSquare);
}
private Shape RandomSquareLocation()
{
int maxXPosition = pictureBox1.Size.Width / playerOne.Width;
int maxYPosition = pictureBox1.Size.Height / playerOne.Height;
return new Shape { X = random.Next(0, maxXPosition), Y = random.Next(0, maxYPosition) };
}
private readonly List<Shape> Square1 = new List<Shape>();
private void GenerateSquare()
{
Shape newSquare = RandomSquareLocation();
while (Square1.Any(square => square.X == newSquare.X && square.Y == newSquare.Y))
{
newSquare = RandomSquareLocation();
}
Square1.Add(newSquare);
}
private Shape RandomSquareLocation()
{
int maxXPosition = pictureBox1.Size.Width / playerOne.Width;
int maxYPosition = pictureBox1.Size.Height / playerOne.Height;
return new Shape { X = random.Next(0, maxXPosition), Y = random.Next(0, maxYPosition) };
}

GenerateSquare只会在pictureBox上的某个地方生成一个Square。至少就我的观点而言,我需要抽象类来实现这一点的原因是。如果需要多个不同的Squeares,则需要反复补充GenerateSquare函数。RandomSquareLocation函数充当正方形产生的位置的基础

我不确定我是否完全理解你的问题。

但我认为你想做的是让你的方法虚拟化。

虚拟方法提供默认实现。它CAN在从基类继承的类中被覆盖。

抽象方法必须由从基类继承的类实现。

已经给出了类似的答案

最新更新