博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ICloneable , MemberwiseClone()

Posted on 2007-05-04 14:44  james.dong  阅读(669)  评论(1编辑  收藏  举报

  public class Emplyee:ICloneable
{
        private string _name = string.Empty;
    private int _id = 0;
    private string _email = string.Empty;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public string Email
    {
        get { return _email; }
        set { _email = value; }
    }

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

    public Emplyee()
    {
    }

    public Emplyee(Emplyee e)
    {
        this._id = e.Id;
        this._name = e.Name;
        this._email = e.Email;
    }
}

public class Company : ICloneable
{
    private Emplyee _e = null;
    public Emplyee E
    {
        get { return _e; }
        set { _e = value; }
    }
    private string _name = string.Empty;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public object Clone()
    {
        Company c = (Company)this.MemberwiseClone();
        c._e = new Emplyee( this._e );
        return c;
    }
}

   public void Main()
{
     Company c1 = new Company();

      c1.E = new Emplyee();
        c1.E.Id = 0;
        c1.E.Email = "x@163.com";
        c1.E.Name = "aaa";
      Company c2 = (Company )c1.Clone();
}