C#反射动态赋值

2018-06-17 19:47:23来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

 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 = 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     }
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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:C#类的成员初始化顺序

下一篇:Xamarin.iOS开发初体验