国产探花免费观看_亚洲丰满少妇自慰呻吟_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

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 同江市| 荣昌县| 额敏县| 江陵县| 册亨县| 西吉县| 宣武区| 奉化市| 乡宁县| 通化市| 武鸣县| 台北市| 临高县| 文昌市| 克什克腾旗| 波密县| 大城县| 南召县| 平顺县| 白沙| 保亭| 瑞昌市| 徐州市| 洛浦县| 简阳市| 六安市| 哈密市| 开原市| 衡阳县| 阳曲县| 湘乡市| 那坡县| 申扎县| 油尖旺区| 冷水江市| 公安县| 广南县| 凤城市| 唐河县| 荔波县| 玉屏|