首页 > 代码库 > C#反射动态赋值

C#反射动态赋值

很多时候我们需要在数据实体层读取数据后赋值到领域模型时往往会产生如下的代码

 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     
View Code

这样的话会产生很多工作量,我们可以使用反射动态为对象赋值,只要属性名一直就可以。

 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 = http://www.mamicode.com/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 =http://www.mamicode.com/ 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     }
View Code

调用方式

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