子类复制父类的值

将子类对象赋给父类对象,是可以的,但反过来就不行。

但是很多时候,子类对象希望能复制父类对象的值,该怎么办呢?

老老实实地一个个属性的赋值,当然是可以的,但这样好像傻了点,尤其是有好几种子对象的时候。

这时可以用泛型 + 反射来搞定。反射,我学艺不精,以为一定要对运行中的DLL来进行读取才行,其实是记错了。

class CAutoCopy<TParent, TChild>
    where TParent : class, new()
    where TChild : class, new()
{
    public TChild AutoCopy(TParent parent)
    {
        TChild child = new TChild();
        var ParentType = typeof(TParent);
        var Properties = ParentType.GetProperties();
        foreach (var Propertie in Properties)
        {
            if (Propertie.CanRead && Propertie.CanWrite)
            {//循环遍历属性
                Propertie.SetValue(child, Propertie.GetValue(parent, null), null);//进行属性拷贝
            }
        }
        return child;
    }
}

我因为考虑可能还有多个方法要用到这些泛型,所以用到泛型类;其实像参考文章那样,直接用泛型方法应该也可以的。

参考文章:

http://www.cnblogs.com/Soar1991/archive/2012/11/04/2754319.html


版权声明:本文为博主原屙文章,喜欢你就担走。

原文地址:https://www.cnblogs.com/leftfist/p/4764274.html