C#反射动态赋值

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

1publicclassA2{3publicstringName {get;set;}4publicintAge {get;set;}5}67publicclassB8{9publicstringName {get;set;}10publicintAge {get;set;}11}1213staticvoidmain(string[] args)14{15A a=newA();16a.Name ="aa";17a.Age =1;18B b =newB();19b.Name =a.Name;20b.Age =a.Age;21}2223

View Code

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

1publicstaticclassCommon2{3publicstaticvoidCopyTo<T>(thisobjectsource, T target)4whereT :class,new()5{6if(source ==null)7return;89if(target ==null)10{11target =newT();12}1314foreach(varPRopertyintarget.GetType().GetProperties())15{16varpropertyValue = source.GetType().GetProperty(property.Name).GetValue(source,null);17if(propertyValue !=null)18{19if(propertyValue.GetType().IsClass)20{2122}23target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty,null, target,newobject[] { propertyValue });24}2526}2728foreach(varfieldintarget.GetType().GetFields())29{30varfieldValue =source.GetType().GetField(field.Name).GetValue(source);31if(fieldValue !=null)32{33target.GetType().InvokeMember(field.Name, BindingFlags.SetField,null, target,newobject[] { fieldValue });34}35}36}37}

View Code

调用方式

staticvoidmain(string[] args)

{

A a=newA();

a.Name="aa";

a.Age=1;

B b=newB();

a.CopyTo(b);

}

View Code

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航