关于用Reflection来实现父类和子类共用一个ICloneable函数

最近在做项目的时候需要用到ICloneable.不过在c#中无法实现内存拷贝。所以必须要对对象中的每一个属性都进行复制.属性太多的时候.一个个的复制显得非常的麻烦.(尤其是当在子类中。又要必须override重新写上一次父类的属性再加上自己的几个属性,所以显得非常麻烦)As Fellowing:

public class A:ICloneable
{
     private int m_a;
     public int INTA
     {
         get
         {
             return m_a;
         }
        set
        {
            m_a = value;
        }
    }
    #region ICloneable Imp
    public virtual object Clone()    
    {
         A newA = new A();
        newA.INTA = INTA;
       return newA;
    }
   #endregion
}

public class B:B
{
     private int m_b;
     public int INTB
     {
         get
         {
             return m_b;
         }
        set
        {
            m_b = value;
        }
    }

    public override object Clone()    
    {
         B newB = new B();
        newB.INTA = INTA;
        newB.INTB = INTB;
       return newB;
    }

}

其实可以使用Reflection的策略.这样可以自动的在父类实现一个ICloneable就可以了,而子类无需重载Clone函数

public class A:ICloneable
{
     private int m_a;
     public int INTA
     {
         get
         {
             return m_a;
         }
        set
        {
            m_a = value;
        }
    }
    #region ICloneable Imp
    public virtual object Clone()    
    {
            Type type = this.GetType();
            ConstructorInfo cinfo = type.GetConstructor(new Type[0]);
            object newObj = cinfo.Invoke(null);
            PropertyInfo[] infos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            foreach (PropertyInfo info in infos)
            {
                if (info.CanRead)
                {
                    if (info.CanWrite)
                    {
                        info.SetValue(newObj, info.GetValue(this, null), null);
                    }
                }
            }
            return newObj;
    }
   #endregion
}

public class B:B
{
     private int m_b;
     public int INTB
     {
         get
         {
             return m_b;
         }
        set
        {
            m_b = value;
        }
    }
}

注意:在这个方法里面.默认的把需要重新复制的Field都暴露成可以set和get的attribute。如果没有那么做.可以用Reflection的其他方法获得Private 的Field进行复值. :-)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值