首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

深度复制也不行,谢了

2012-01-07 
深度复制也不行,在线等。谢了class City{public int[] mannew int[2]public int population 10Country

深度复制也不行,在线等。谢了
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;         }     } 

热点排行