国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#反射動態賦值

2019-11-14 16:36:12
字體:
來源:轉載
供稿:網友

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

 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

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灵山县| 习水县| 来宾市| 民勤县| 商水县| 余庆县| 龙江县| 文化| 营山县| 高陵县| 全椒县| 石棉县| 东兰县| 吉安县| 巨野县| 河南省| 丽水市| 武陟县| 修水县| 长海县| 中西区| 和龙市| 朔州市| 屯门区| 翁牛特旗| 肥西县| 博爱县| 伊川县| 威远县| 图们市| 苏尼特左旗| 楚雄市| 白银市| 都兰县| 泸西县| 平遥县| 南昌市| 南溪县| 格尔木市| 怀仁县| 客服|