0

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

   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")
  };

现在,我创建了一个列表,并在此处添加了上述内容之一的副本:-

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

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

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

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

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

有任何想法吗?

4

3 回答 3

1

你可以让你的类实现ICloneable接口并实现你自己的Clone()方法。

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

FleetShips.Add((Ship)AllShips[(int)ShipType.Fighter].Clone());
于 2013-11-13T05:52:36.903 回答
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 是什么

于 2013-11-13T06:06:35.900 回答
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]));
于 2013-11-13T06:01:46.763 回答