码迷,mamicode.com
首页 > Web开发 > 详细

.net 父类值赋给子类

时间:2019-05-11 18:10:07      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:where   dcl   优点   arp   缺点   bool   anr   value   字段   

1、最简单的方式,反射+泛型

    优点:字段修改时,无需更改代码,只需要更新实体即可

    缺点:因为用到反射,可能效率会稍微弱那么一点点,没有实际用太多字段测试

public static cClass ParentCopyToChild<pClass,cClass>(pClass parent) where cClass: class,pClass,new()
        {
            //ChildClass child = new ChildClass();
            cClass child = new cClass();

            var ParentType = typeof(pClass);
            
            var Properties = ParentType.GetProperties();
            
            foreach (var Propertie in Properties)
            {
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                }
            }
            
            return child;
        }

2、子类中加入赋值操作

public class TreeViewOrgEx:TreeViewOrg
    {
        public long ParentCode = 0;
        public string TypeName = string.Empty;

        //树开启多选框时,此属性决定是否默认选中
        public bool isChecked;
        //树开启多选框时,此属性决定多选框是否禁用
        public bool chkDisabled;
        //树是否默认展开
        public bool open = true;

        public int ISRole = 0;

        //需要一个默认构造函数
        public TreeViewOrgEx()
        {

        }

        public TreeViewOrgEx(TreeViewOrg orgBase)
        {
            this.ID = orgBase.ID;
            this.OrgCode = orgBase.OrgCode;
            this.OrgName = orgBase.OrgName;
            this.OrgLevel = orgBase.OrgLevel;
            this.OrgType = orgBase.OrgType;
            this.SourceCode = orgBase.SourceCode;
            this.UpdateTime = orgBase.UpdateTime;
        }
    }

  赋值

TreeViewOrg tempOrg = new TreeViewOrg();

tempOrg.OrgCode = 10000000000;

TreeViewOrgEx orgEx = new TreeViewOrgEx(tempOrg);

orgEx.ParentCode = 20000000000;

  3、写方法操作

public void TreeViewOrgToTreeViewOrgEx(TreeViewOrg org, TreeViewOrgEx orgEx)
        {
            orgEx.ID = org.ID;
            orgEx.OrgCode = org.OrgCode;
            orgEx.OrgName = org.OrgName;
            orgEx.OrgLevel = org.OrgLevel;
            orgEx.OrgType = org.OrgType;
            orgEx.SourceCode = org.SourceCode;
           orgEx.UpdateTime = org.UpdateTime;
        }

  

.net 父类值赋给子类

标签:where   dcl   优点   arp   缺点   bool   anr   value   字段   

原文地址:https://www.cnblogs.com/zhoushangwu/p/10849330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!