c#如何将类添加到类数组中的列表中

时间:2013-11-13 05:49:11

标签: c# arrays list class templates

我有一个类来定义例如一艘船,然后我有一个带有一些默认参数的类的数组但是稍后我希望能够使用一个预定义的示例添加到该类的列表中。我不知道如何将预定义类添加到列表中,同时创建它的副本而不是指向原始数组的指针。以下是有希望完全清楚的代码。

   public enum ShipType
    {
      Capital,
      Cruiser,
      Frigate,
      Fighter,
      Colony,
      NumShipTypes
    }
    public class Ship
    {
      public Vector3 ShipPosition;
      public ShipType Type;
      public string DesignName;
      public Ship(ShipType type,string designame)
      {
        Type = type;
        DesignName = designame;
        ShipPosition = Vector3.zero;
      }
    }

然后是我的默认类型数组: -

public Ship[] AllShips = new Ship[(int)ShipType.NumShipTypes]
  { 
    new Ship(ShipType.Capital,"MassiveOne"),
    new Ship(ShipType.Cruiser,"MediumOne"),
    new Ship(ShipType.Frigate,"SmallerOne"),
    new Ship(ShipType.Fighter,"TinyOne"),
    new Ship(ShipType.Colony,"Mayflower")
  };

现在我创建一个列表和heres,我想在其中添加上述其中一个的副本: -

public List<Ship> FleetShips = new List<Ship>(); 

FleetShips.Add(AllShips[(int)ShipType.Fighter]); 

但这似乎只是添加一个引用或指向数组中的引用或指针。我需要的是这样的东西,但这确实有效: -

FleetShips.Add(new AllShips[(int)ShipType.Fighter]()); 

但是这给了我“是一个字段但是像类型一样使用”错误

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以让您的类实现ICloneable界面并实现您自己的Clone()方法。

然后,当您想将它添加到您的收藏中时,您可以执行此操作

FleetShips.Add((Ship)AllShips[(int)ShipType.Fighter].Clone());

答案 1 :(得分:0)

另一种可能性是将复制构造函数添加到Ship-class。

public class Ship
{
  public Vector3 ShipPosition;
  public ShipType Type;
  public string DesignName;
  public Ship(ShipType type,string designame)
  {
    Type = type;
    DesignName = designame;
    ShipPosition = Vector3.zero;
  }
  //copy-constructor
  public Ship(Ship other)
  {
    Type = other.Type;
    DesignName = other.DesignName;
    ShipPosition = Vector3.zero;
  }
}

当你想要添加你所做的船的副本时

FleetShips.Add(new Ship(AllShips[(int)ShipType.Fighter]));

答案 2 :(得分:0)

实施ICloneable。

   public class Ship: ICloneable
    {
        public Vector3 ShipPosition;
        public ShipType Type;
        public string DesignName;
        public Ship(ShipType type, string designame)
        {
            Type = type;
            DesignName = designame;
            ShipPosition = Vector3.zero;
        }


        public object Clone()
        {
           return this.MemberwiseClone();
        }
    }

添加

FleetShips.Add(AllShips[(int)ShipType.Fighter].Clone() as Ship); 

编辑:可能仍然是一个问题,具体取决于Vector3是什么