如何从多个继承自spaceships父类的子类中随机生成实例并存入二叉树
实现方案
1 原代码修复
现有代码存在两个明显错误:
- 基类构造函数赋值顺序错误:先给实例字段赋值了传入参数,后续生成的随机值只修改了局部变量,不会同步到实例属性
- 非静态Random实例在短时间批量创建对象时,会因为系统随机种子生成间隔问题出现大量重复属性,需要改为静态实例
修复后的代码如下:
public class spaceships { // 改为公共属性方便外部读取,可根据需求调整访问级别 public int cost; public int combatPower; // Random改为静态保证随机数不重复 private static Random rand = new Random(); // 两个属性都是随机生成,不需要外部传参 public spaceships() { // 直接给实例字段赋值随机数 this.cost = rand.Next(10000, 1000000); this.combatPower = rand.Next(20, 100); } } // 子类构造函数直接调用父类无参构造即可 public class Patrol : spaceships { public Patrol() : base() { // 子类有独有属性可在这里补充初始化 } } // 剩下的4个子类按照同样规则定义即可,示例: public class Fighter : spaceships { } public class Bomber : spaceships { } public class Transport : spaceships { } public class Explorer : spaceships { }
2 随机生成多子类实例
你可以根据自己的需求选择两种实现方式:
反射实现(适合后续可能新增子类的场景)
// 存储所有子类的类型 private static Type[] shipTypes = new Type[] { typeof(Patrol), typeof(Fighter), typeof(Bomber), typeof(Transport), typeof(Explorer) }; // 生成指定数量的随机飞船实例 public static List<spaceships> GenerateRandomShips(int countPerType = 1) { List<spaceships> ships = new List<spaceships>(); foreach (var type in shipTypes) { for (int i = 0; i < countPerType; i++) { // 反射创建对应子类的实例 spaceships ship = (spaceships)Activator.CreateInstance(type); ships.Add(ship); } } return ships; }
硬编码实现(适合子类固定的场景,性能更高)
public static List<spaceships> GenerateRandomShips(int countPerType = 1) { List<spaceships> ships = new List<spaceships>(); for (int i = 0; i < countPerType; i++) { ships.Add(new Patrol()); ships.Add(new Fighter()); ships.Add(new Bomber()); ships.Add(new Transport()); ships.Add(new Explorer()); } return ships; }
3 实例存入二叉树
这里提供一个简单的二叉搜索树实现,你可以根据自己的排序规则(比如按cost、combatPower排序)调整比较逻辑:
// 二叉树节点定义 public class TreeNode { public spaceships Ship { get; set; } public TreeNode Left { get; set; } public TreeNode Right { get; set; } public TreeNode(spaceships ship) { Ship = ship; Left = Right = null; } } // 二叉树实现 public class ShipBinaryTree { private TreeNode root; // 插入节点的比较规则:这里以cost从小到大排序,可自行修改 public void Insert(spaceships ship) { root = InsertRecursive(root, ship); } private TreeNode InsertRecursive(TreeNode current, spaceships ship) { if (current == null) { return new TreeNode(ship); } // 按cost比较,小的放左子树,大的放右子树 if (ship.cost < current.Ship.cost) { current.Left = InsertRecursive(current.Left, ship); } else if (ship.cost > current.Ship.cost) { current.Right = InsertRecursive(current.Right, ship); } return current; } }
调用示例
// 生成每个子类1个实例,总共5个 var ships = GenerateRandomShips(1); // 初始化二叉树 var tree = new ShipBinaryTree(); // 逐个插入二叉树 foreach (var ship in ships) { tree.Insert(ship); }
内容的提问来源于stack exchange,提问作者ismaiaka
相关产品推荐
相关产品推荐

