日期:2014-05-18  浏览次数:21266 次

深度复制也不行,在线等。谢了
class City 
  {
  public int[] man=new int[2];
  public int population = 10;
  Country newCountry;

  public City(Country newCountry)
  {
  this.newCountry = newCountry;
  }
   

  public void Step()
  {
  man[0] = 10;
  population = 20;
  }
  }
 class Country:ICloneable
  {
  public City[] Cities;

  public Country(int index)
  {
  Cities =new City[index];
  }

  public object Clone()
  {
  Country newCountry = new Country(this.Cities.Length);
  for (int i = 0; i < this.Cities.Length; i++)
  {
  newCountry .Cities[i]=this.Cities [i];

  }
  return newCountry;
  }
  }
 class Program
  {
  static void Main(string[] args)
  {
  Country country1 = new Country(1);
  country1.Cities[0] = new City(country1 );
   
  Country tempCoutry;
  tempCoutry = (Country)country1.Clone();  
   
  tempCoutry.Cities[0].Step();
  }
  }
  // tempCountry 变, country1就变了, 搞不懂,等浅度复制时问题一致


------解决方案--------------------
C# code

    class Country:ICloneable 
    { 
        public City[] Cities; 

        public Country(int index) 
        { 
            Cities =new City[index]; 
        } 

        public object  Clone() 
        {
            Country newCountry = new Country(this.Cities.Length); 
            for (int i = 0; i  < this.Cities.Length; i++) 
            {
                newCountry.Cities[i] = new City(this);
                newCountry.Cities[i].population = this.Cities [i].population;
                newCountry.Cities[i].man[0] = this.Cities[i].man[0];
                newCountry.Cities[i].man[1] = this.Cities[i].man[1];
            } 
            return newCountry; 
        } 
    }