【问题标题】:Abstract class from functions, learning OOP函数抽象类,学习OOP
【发布时间】:2021-07-07 08:19:08
【问题描述】:

论坛的新手,我被困在从一个非常基本的函数创建一个抽象类的逻辑上。我知道继承和覆盖如何与抽象类一起工作,但我无法弄清楚将此函数转换为抽象类的逻辑。任何帮助将不胜感激。

除此之外,我这样做是为了帮助我了解基础知识并查看我应该应用哪些其他选项或良好做法。再次感谢您的帮助。

代码:

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 将在图片框的某处生成一个 Square。至少在我看来,为什么我需要抽象类的原因是。如果需要多个不同的 Squeares,GenerateSquare 函数需要一遍又一遍地补充。 RandomSquareLocation 函数充当方块生成位置的基础

【问题讨论】:

  • 您好,欢迎您,恐怕您根本不清楚您要做什么,也不知道它与抽象方法/类的关系。
  • @Jamiec 我希望这能澄清如果不是我很抱歉在这方面是个菜鸟并再次提出错误的问题或提供错误的代码 sry
  • 你也可以发布类定义吗?
  • 从外观上看,您不需要抽象类。 GenerateSquare 相当具体。如果你有一个 GenerateShape 函数,那将是不同的,你在不同的类上实现它(即,用于 Squares、Circles 等)
  • 我同意,这段代码对我来说“需要抽象”也没什么

标签: c# oop abstract-class


【解决方案1】:

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

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

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

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

A similar answer was already given here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多