【问题标题】:How to initialize objects of array which has been created dynamically?如何初始化动态创建的数组对象?
【发布时间】:2013-09-03 07:13:24
【问题描述】:
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
此方法的可传递类型 bishop、knight 等
其实我现在不明白如何初始化对象。我不能只输入 sideA[i] = new first.GetType()(constructor parameters) 并理解原因,但我不明白如何解决这个问题

【问题讨论】:

  • 你确定你的代码是 C# 的吗?具有首字母小且独立功能的类...
  • 您使用哪种编程语言??
  • @Kyle C# 命名风格不好,看看System.Array.CreateInstance
  • 你在使用polymorphism吗?您应该创建一个名为 figure 的基本接口(根据国际象棋图形命名的其他类),然后让其他类实现此接口。这允许您将任何数字作为参数传递。
  • 感谢批评,我一定会学习C#命名约定!而这段代码只是我案例的一个模型

标签: c# arrays initialization


【解决方案1】:

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

我假设,您的方法 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 { }

【讨论】:

    【解决方案2】:

    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 的索引器语法。

    【讨论】:

    • +1 仿制药样品...也感谢您修改我的帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2022-10-14
    • 2020-04-21
    相关资源
    最近更新 更多