zoukankan      html  css  js  c++  java
  • 子类复制父类的值

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

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

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

    这时可以用泛型 + 反射来搞定。反射,我学艺不精,以为一定要对运行中的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


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

  • 相关阅读:
    Vue状态管理
    Vue延迟点击
    Vue路由
    简单的队列应用
    Uncaught SyntaxError: Unexpected token )
    视频转码
    判断是否为视频文件
    Press ^C at any time to quit.
    Node.js学习
    YUM安装LAMP与LNMP
  • 原文地址:https://www.cnblogs.com/leftfist/p/4764274.html
Copyright © 2011-2022 走看看