.net 父类值赋给子类

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;
        }

  

转载于:https://www.cnblogs.com/zhoushangwu/p/10849330.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值