/**************************************
* 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
还没有评论,来说两句吧...