Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从一堆类(herited类)创建随机对象_C#_Random_Binary Search Tree - Fatal编程技术网

C# 如何从一堆类(herited类)创建随机对象

C# 如何从一堆类(herited类)创建随机对象,c#,random,binary-search-tree,C#,Random,Binary Search Tree,很抱歉,如果有类似的问题,请尝试搜索,但没有找到适合我使用的适当响应 我有5个类,它们来自一个类(spaceshipclass),我需要从每个类创建随机对象,并将它们存储在二叉树中。 对于每个对象,两个随机整数,如下面的代码所示 public class spaceships { int cost; int combatPower; private Random rand = new Random(); public spaceships(int cost,

很抱歉,如果有类似的问题,请尝试搜索,但没有找到适合我使用的适当响应

我有5个类,它们来自一个类(spaceshipclass),我需要从每个类创建随机对象,并将它们存储在二叉树中。 对于每个对象,两个随机整数,如下面的代码所示

public class spaceships
{
    int cost;
    int combatPower;
    private Random rand = new Random();

     public spaceships(int cost, int combatPower)
    {
        this.cost = cost;
        this.combatPower = combatPower;

        cost = rand.Next(10000, 1000000);
        combatPower = rand.Next(20, 100);

    }

} 

public class Patrol : spaceships
{
        public Patrol (int cost,int combatPower) : base(cost,combatPower)
        {
        }
}
第二个类是继承的类之一


我希望有人能帮助我。

似乎在所需功能和发布的代码之间存在断开,因为您的
spaceships
类在其构造函数中包含
cost
combatPower
中的一个,但随后忽略该功能并计算这些值本身。因此,我将忽略这个特定的实现,在构建随机对象之前,按照您的问题标题的要求,继续计算这些值。请记住,我的解决方案允许您完全删除spaceships类的私有
随机rand
字段

您可以使用一个简单的
switch
语句来确定要创建哪种类型的飞船,然后将它们添加到您的集合中(您提到了一个二元搜索树,但这是一个实现细节,在这里并不重要,只要它是
spaceships
类型,以支持您的问题提到的多态性)

Random rand=new Random();
对于(int i=0;i
cost=rand。接下来(10000,1000000)
将为方法参数
cost
分配一个随机数,该参数不再使用。
Random rand = new Random();

for (int i = 0; i < numSpaceshipsRequired; i++)
{
    int typeOfSpaceship = rand.Next(0, 5);
    int cost = rand.Next(10000, 1000000);
    int combatPower = rand.Next(20, 100);
    
    switch (typeOfSpaceship)
    {
        case 0:
            collection.Add(new Patrol(cost, combatPower));
            break;
        case 1:
            collection.Add(new Cruiser(cost, combatPower));
            break;
        case 2:
            collection.Add(new Frigate(cost, combatPower));
            break;
        case 3:
            collection.Add(new Fighter(cost, combatPower));
            break;
        case 4:
            collection.Add(new Stealth(cost, combatPower));
            break;
    }
}