gpt4 book ai didi

c# - 无法访问继承的全局变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:55 28 4
gpt4 key购买 nike

我正在编写一个小程序,该程序应该从正方形的底部创建不同形状的房间。这些形状应该继承自包含其顶点列表的正方形。

Room(父类)代码:

class Room
{
private List<Point> vertices;
private int oX;
private int oY;
private int width;
private int height;

public Room(int oX, int oY, int width, int height)
{
vertices = new List<Point>();
addVertice(new Point(oX, oY));
addVertice(new Point(oX + width, oY));
addVertice(new Point(oX, oY + height));
addVertice(new Point(oX + width, oY + height));

this.width = width;
this.height = height;
}
}

然后我从 Room 继承了 LShape,但是 Visual Studio 说无法访问 vertices 变量由于其保护级别。

LShape(子)类的代码

class LShape: Room
{
public LShape(int oX, int oY, int width, int height, List<Point> verticesList)
{
vertices = verticesList;
}
}

根据我找到的所有教程,这应该有效,即使父级成员是私有(private)的也是如此。

有人可以向我解释我的错误在哪里,或者我在哪里误解了这些概念吗?另外,如果您有关于继承的任何好的教程,我将不胜感激。

谢谢。

最佳答案

According to all the tutorials I found, this should be working, even if the Parent's members are private.

不,私有(private)成员只能在声明类型的程序文本中访问。因此,如果您将 LShape 声明为 Room 中的嵌套 类型,那将起作用 - 但否则它将不起作用。如果它是 protected 成员,您就可以访问它,但老实说,我建议无论如何都将其保持为 private - 相反,将顶点传递给构造函数。

请注意,您的 LShape 构造函数也需要链接到 Room 中的可访问构造函数(或另一个 LShape 构造函数,但最终它必须链接到 Room)。

关于c# - 无法访问继承的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37394749/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com