C# 父类和子类的相互转换

本文介绍了一种在C#中实现对象从父类到子类及从子类到父类转换的方法,通过使用反射机制,实现了属性的自动复制,提高了代码的复用性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**************************************
 * ClsHelper.cs
 **************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ClsHelper {
    public class ClsHelper {
        /// <summary>
        /// 从父类到子类转换
        /// </summary>
        /// <typeparam name="TP">父类</typeparam>
        /// <typeparam name="TC">子类</typeparam>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static TC CopyFromParent<TP, TC> (TP parent) where TC : TP, new () where TP : new () {
            if (parent == null) return default (TC);
            var child = new TC ();
            typeof (TP).GetProperties ().Where (p => p.CanRead && p.CanWrite).ToList ()
                .ForEach (p => p.SetValue (child, p.GetValue (parent, null), null));
            return child;
        }

        /// <summary>
        /// 从子类到父类
        /// </summary>
        /// <typeparam name="TP">父类</typeparam>
        /// <typeparam name="TC">子类</typeparam>
        /// <param name="child"></param>
        /// <returns></returns>
        public static TP CopyToParent<TP, TC> (TC child) where TC : TP, new () where TP : new () {
            if (child == null) return default (TP);
            var parent = new TP ();
            typeof (TP).GetProperties ().Where (p => p.CanRead && p.CanWrite).ToList ()
                .ForEach (p => p.SetValue (parent, p.GetValue (child, null), null));
            return parent;
        }
    }
}
/**************************************
 * A.cs 父类
 **************************************/
using System;

namespace ClsHelper {
    public class A {
        public string a1 { get; set; }
    }
}

 

/**************************************
 * B.cs 子类
 **************************************/
using System;

namespace ClsHelper {
    public class B : A {
        public string b1 { get; set; }
    }
}

 

/**************************************
 * Program.cs
 **************************************/
using System;

namespace ClsHelper {
    class Program {
        static void Main (string[] args) {
            A aa = new A ();
            aa.a1 = "aa_a1";

            var bb = ClsHelper.CopyFromParent<A, B> (aa);
            bb.b1 = "bb_b1";
            Console.WriteLine (bb.a1);

            bb.a1 = "bb_a1";
            aa = ClsHelper.CopyToParent<A, B> (bb);
            Console.WriteLine (aa.a1);
        }
    }
}

 

>> aa_a1
>> bb_a1

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieZhengChina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值