在子类中访问列表<object>

时间:2015-05-07 18:04:57

标签: c# list inheritance access-modifiers

我正在为交通编写模拟。我正在上课,可以放在gui上的物品(十字路)。

一种方法使用List并简单地使用构造函数将交通灯组(同步交通灯)添加到列表List tlg。

public TrafficLightGroup(int tlgID, Direction? direction, Lane lane1, Lane? lane2)
    {
        this.tlgID = tlgID;
        this.lane1 = lane1;
        this.lane2 = lane2;
        this.direction = direction;
    }

class Item
{
public virtual void SetTrafficLightSystem()
    {
        tlg.Add(new TrafficLightGroup(1, Direction.West, Lane.Left, Lane.Straight));
        tlg.Add(new TrafficLightGroup(2, Direction.West, Lane.Right, null));

        tlg.Add(new TrafficLightGroup(3, Direction.South, Lane.Left, Lane.Straight));
        tlg.Add(new TrafficLightGroup(4, Direction.South, Lane.Right, null));

        tlg.Add(new TrafficLightGroup(1, Direction.East, Lane.Left, Lane.Straight));
        tlg.Add(new TrafficLightGroup(2, Direction.East, Lane.Right, null));

        tlg.Add(new TrafficLightGroup(3, Direction.North, Lane.Left, Lane.Straight));
        tlg.Add(new TrafficLightGroup(4, Direction.North, Lane.Right, null));


    }
}

现在我想从名为CrossingPedestrians的子类访问相同的列表并更改基本方法。我如何访问列表?我使用了defaul get;并设定;现在,但我读到这不是一个好的解决方案。

这里是子类

class CrossingPedestrians : Item
{
    public override void SetTrafficLightSystem()
    {
        base.SetTrafficLightSystem();                       
        Tlg.Add(new TrafficLightGroup(5, null, Lane.Pedestrian, null));
    }

那么,我怎样才能解决因访问者而无法正确访问列表的问题,我认为访问者不会以正确的方式运行。

1 个答案:

答案 0 :(得分:1)

您应该向我们展示Item课程的相关部分。

无论如何,您可能担心将Tlg作为财产公开。这本身并没有错,你只需要protected

protected List<TrafficLightGroup> Tlg {get; set;}

这样子类仍然可以访问它,但外部世界不能。

相关问题