如何为每个新房间对象分配其自己的项目对象列表

时间:2016-09-15 10:19:22

标签: c# list object

我正在尝试使用Room创建每个InteractiveObjects我创建的任何工作?或者我是否需要为每个房间制作一个清单?我真的不喜欢这样做

class Room
{
    private string Name { get; set; }
    private string Description { get; set; }

    private static List<InteractiveObjects> RoomObjects { get; set; } = new List<InteractiveObjects>();

    InteractiveObjects woodenDoor = new InteractiveObjects()
    {
        Name = "Wooden Door",
        Description = "Looks like it's not very durable",
        Type = "Door",
        Breakable = true,
        FitsInInventory = false,
        Locked = true
    };

    public static Room SmallRoom = new Room()
    {
        Name = "Small Room",
        Description = "it's a small room with only one wooden door and a ceiling light",
        //RoomObjects.Add(woodenDoor) DOES NOT WORK
    };
    public static Room Cellar = new Room()
    {
        Name = "Cellar",
        Description = "Some Description",
        //RoomObjects.Add(someObject) DOES NOT WORK
    };
}

3 个答案:

答案 0 :(得分:2)

从RoomObjects中删除静态以使其成为实例字段。

答案 1 :(得分:2)

您的第一个问题是RoomObjects被声明为static,因此您对所有List<InteractiveObjects>个实例使用相同的Room实例。

第二个是错误的语法。您无法在对象初始值设定项中显式调用Add。但编译器会将此语法转换为对RoomObjectsAdd

的调用
public static Room Cellar = new Room()
{
    Name = "Cellar",
    Description = "Some Description",
    RoomObjects = { someObject1, someObject2 }
};

答案 2 :(得分:0)

这取决于您需要的RoomObjects列表。它是否应包含属于Room的{​​{1}}的{​​{1}},或者是否应包含所有InteractiveObjects的列表,无论其Room如何使用?

如果您的标题显示您希望每个InteractiveObjects只列出Room个商品的列表,则每个房间需要一个列表,并且您必须删除{{ 1}}来自Room定义。