很多時候我們需要在數據實體層讀取數據后賦值到領域模型時往往會產生如下的代碼

1 public class A 2 { 3 public string Name {get;set;} 4 public int Age {get;set;} 5 } 6 7 public class B 8 { 9 public string Name {get;set;} 10 public int Age {get;set;} 11 } 12 13 static void main(string[] args) 14 { 15 A a= new A(); 16 a.Name = "aa"; 17 a.Age = 1; 18 B b = new B(); 19 b.Name = a.Name; 20 b.Age = a.Age; 21 } 22 23
這樣的話會產生很多工作量,我們可以使用反射動態為對象賦值,只要屬性名一直就可以。

1 public static class Common 2 { 3 public static void CopyTo<T>(this object source, T target) 4 where T : class,new() 5 { 6 if (source == null) 7 return; 8 9 if (target == null) 10 { 11 target = new T(); 12 } 13 14 foreach (var property in target.GetType().GetProperties()) 15 { 16 var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null); 17 if (propertyValue != null) 18 { 19 if (propertyValue.GetType().IsClass) 20 { 21 22 } 23 target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue }); 24 } 25 26 } 27 28 foreach (var field in target.GetType().GetFields()) 29 { 30 var fieldValue = source.GetType().GetField(field.Name).GetValue(source); 31 if (fieldValue != null) 32 { 33 target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue }); 34 } 35 } 36 } 37 }
調用方式

static void main(string[] args) { A a = new A(); a.Name = "aa"; a.Age = 1; B b = new B(); a.CopyTo(b); }