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

迷南。 2023-02-13 03:16 112阅读 0赞
  1. /**************************************
  2. * ClsHelper.cs
  3. **************************************/
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Xml.Linq;
  9. namespace ClsHelper {
  10. public class ClsHelper {
  11. /// <summary>
  12. /// 从父类到子类转换
  13. /// </summary>
  14. /// <typeparam name="TP">父类</typeparam>
  15. /// <typeparam name="TC">子类</typeparam>
  16. /// <param name="parent"></param>
  17. /// <returns></returns>
  18. public static TC CopyFromParent<TP, TC> (TP parent) where TC : TP, new () where TP : new () {
  19. if (parent == null) return default (TC);
  20. var child = new TC ();
  21. typeof (TP).GetProperties ().Where (p => p.CanRead && p.CanWrite).ToList ()
  22. .ForEach (p => p.SetValue (child, p.GetValue (parent, null), null));
  23. return child;
  24. }
  25. /// <summary>
  26. /// 从子类到父类
  27. /// </summary>
  28. /// <typeparam name="TP">父类</typeparam>
  29. /// <typeparam name="TC">子类</typeparam>
  30. /// <param name="child"></param>
  31. /// <returns></returns>
  32. public static TP CopyToParent<TP, TC> (TC child) where TC : TP, new () where TP : new () {
  33. if (child == null) return default (TP);
  34. var parent = new TP ();
  35. typeof (TP).GetProperties ().Where (p => p.CanRead && p.CanWrite).ToList ()
  36. .ForEach (p => p.SetValue (parent, p.GetValue (child, null), null));
  37. return parent;
  38. }
  39. }
  40. }
  41. /**************************************
  42. * A.cs 父类
  43. **************************************/
  44. using System;
  45. namespace ClsHelper {
  46. public class A {
  47. public string a1 { get; set; }
  48. }
  49. }
  50. /**************************************
  51. * B.cs 子类
  52. **************************************/
  53. using System;
  54. namespace ClsHelper {
  55. public class B : A {
  56. public string b1 { get; set; }
  57. }
  58. }
  59. /**************************************
  60. * Program.cs
  61. **************************************/
  62. using System;
  63. namespace ClsHelper {
  64. class Program {
  65. static void Main (string[] args) {
  66. A aa = new A ();
  67. aa.a1 = "aa_a1";
  68. var bb = ClsHelper.CopyFromParent<A, B> (aa);
  69. bb.b1 = "bb_b1";
  70. Console.WriteLine (bb.a1);
  71. bb.a1 = "bb_a1";
  72. aa = ClsHelper.CopyToParent<A, B> (bb);
  73. Console.WriteLine (aa.a1);
  74. }
  75. }
  76. }
  77. >> aa_a1
  78. >> bb_a1

发表评论

表情:
评论列表 (有 0 条评论,112人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java 转换

    Java 子类向父类转换  需求:数据库查出来的数据不足与展示给前端,需要配合其他业务逻辑处理,增加一些字段展示给前端。 首先google一把, 点进去都是失望而归~,