如何初始化已动态创建的数组的对象

本文关键字:数组 对象 创建 动态 初始化 | 更新日期: 2023-09-27 18:30:03

class bishop:unit {}
class knight:unit {}
class peasant:unit {}
void Battle(unit first, unit second, byte firstAmount, byte secondAmount)
{
  System.Array sideA = System.Array.CreateInstance(first.GetType(),firstAmount);
  for(int i=0; i< firstAmount; i++) 
  { 
   sideA[i] = ???
  }
}

在我的最后一个问题中,我在创建动态数组时遇到了问题,这是我的下一步问题! :D
此方法的可通行类型 主教、骑士等
实际上我现在不明白如何初始化对象。我不能只输入 sideA[i] = 新的第一。GetType(((构造函数参数(并了解原因,但我不明白如何解决这个问题

如何初始化已动态创建的数组的对象

这是非常非常糟糕的设计。

我假设,您的方法Battle可能是类Game的实例方法,您没有提供给我们。

然后,我强烈建议,Battle方法不应创建它所处理对象的实例。它应该只带走他们并进行战斗行动(计算生命等(。

因此,在其他地方创建这些对象,然后将它们发布到方法中。

class Game
{
    List<Bishop> bishops = new List<Bishop>() { new Bishop(..), ... };
    List<Knight> knights = new List<Knight>() { new Knight(..), ... };
    void Battle(List<Unit> first, List<Unit> second)
    {
        foreach(var f in first)
        {
            // get random unit from the second collection and attack him
            f.Attack(GetRandomKnight(second)); 
        }
    }
    public void StartBattle()
    {
        Battle(bishop, knights);
    }
}

此外,请确保使用正确的 C# 命名。类的名称应以大写字母开头。

class Unit
{
    public virtual void Attack(Unit enemy)
    {
        // default attack
        Kick(enemy);
    }
    protected Kick(Unit enemy) { ... }
}
class Bishop : Unit { }

>Ondrej有一个很好的答案。只是为了帮助你处理数组,除非有充分的理由,否则你永远不应该使用反射。我认为你没有理由在这里这样做。您可以使用典型的 new 关键字来实例化数组。

void Battle(unit first, unit second, byte firstAmount, byte secondAmount)
{
  var sideA = new unit[firstAmount];
  for(int i=0; i< sideA.Length; i++) 
  { 
    sideA[i] = ???
  }
}

如果实例化数组确实应该为运行时类型 first ,那么您可以依赖泛型。

void Battle<T1, T2>(T1 first, T2 second, byte firstAmount, byte secondAmount) 
                   where T1 : unit where T2 : unit
{
  var sideA = new T1[firstAmount];
  for(int i=0; i< sideA.Length; i++) 
  { 
    sideA[i] = ???
  }
}

解决问题的完全动态方式将是SetValueGetValue

void Battle(unit first, unit second, byte firstAmount, byte secondAmount)
{
  var sideA = Array.CreateInstance(first.GetType(),firstAmount);
  for(int i=0; i< firstAmount; i++) 
  { 
   sideA.SetValue(???, i);
   sideA.GetValue(i); //to get the value back.
  }
}

基本上你不会得到System.Array的索引器语法。