题目:
ICloneable 接口是.NET Framework 类库中定义的用于实现克隆(深拷贝:即用与现有实例相同的值创建类的新实例。)操作的接口。
该接口定义如下
Interface ICloneable 
{
object  Clone();
}
对于如下定义的一个C#聚合类, 请将其改造为实现ICloneable接口的类。
class CAggregate
{
private:
ArrayList list;
public:
CAggregate() {list = new ArrayList; }
public void Append(Object mObj) {list.Add(mObj); }
}我的答案:
    class CAggregate
    {
        private
            ArrayList list;        public
            CAggregate() {list = new ArrayList(); }        public void Append(Object mObj) {list.Add(mObj); }        public CAggregate clone()
        {
            CAggregate newObj = new CAggregate();
            newObj.list = this.list;
            return newObj;
        }

    }是否正确?

解决方案 »

  1.   


      newObj.list = this.list; 这里有问题,我觉得不妥,深层拷贝是拷贝出一个和原对象完全没有关系的一个对象吧。
    上面这个赋值的话,list里的内容指向的是同一个内存块,也就是说,拷贝出来的对象和原对象共享着同一个ArrayList中的内容。所以我想应该把原对象里面list里的内容循环赋值给newObj.listpublic CAggregate clone()
    {
          CAggregate newObj = new CAggregate();
          //newObj.list = this.list;
          newObj.list = new ArrayList();
          for(int i = 0 ; i < this.list.length ; i++)
          {
              newObj.list[i] = this.list[i];
          }
          return newObj;
    } 但是原对象list里面存放的应该都是简单数据类型,而不是对象数据类型,因为对象之间的赋值都是引用赋值,赋值以后两个对象指向的是同一个内存。如果是list里面真的是对象的话那可能就比较复杂,需要进行递归操作,进入对象检查他的成员变量,如果是简单数据类型最好了,不是的话就继续递归下去吧
      

  2.   

    改了一下:        public CAggregate clone()
            {
                CAggregate newObj = new CAggregate();
                newObj.list = new ArrayList();
                foreach (object obj in this.list)
                    newObj.list.Add(obj);
                return newObj;
            }