-1

我得到了一个父类项目和一些继承自他们的子类,如剑、希尔德等。我现在想编写一个返回一个类似这样的随机项目的函数。

int randomNumber = random()
return ItemList[randomNumber]

但是如何看起来是一种优雅的方式来填充 ItemList ?有没有办法在没有 x 行的情况下填充 ItemList

itemlist.append(new Sword);
itemList.append(new Shild);
itemList.append(new boots);

……等一个?

4

1 回答 1

2

您可以使用集合初始化程序来简化它:

itemList = new List<ParentClass>{
    new Sword(),
    new Shield(),
    new Boots()
};

如果对象也需要一些初始值,您可以将其与对象初始化器结合使用

itemList = new List<ParentClass>{
    new Sword { Length = 50, Name = "Excalibur" },
    new Shield { Strength = 95 },
    new Boots { Size = 45 }
};

切勿Random在紧密循环中创建对象。它用当前时间初始化自己。由于 PC 时钟的滴答声相当缓慢,因此它可能会连续多次返回相同的随机数。最好使它成为类级别的静态只读对象。

private static readonly Random random = new Random();

然后你可以得到一个列表范围内的索引

int index = random.Next(itemList.Count);
var gameObject = itemList[index];
于 2020-12-01T12:31:14.337 回答