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