C#反射动态赋值

时间:2023-03-10 04:47:15
C#反射动态赋值

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

 public class A
{
public string Name {get;set;}
public int Age {get;set;}
} public class B
{
public string Name {get;set;}
public int Age {get;set;}
} static void main(string[] args)
{
A a= new A();
a.Name = "aa";
a.Age = ;
B b = new B();
b.Name = a.Name;
b.Age = a.Age;
}

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

 public static class Common
{
public static void CopyTo<T>(this object source, T target)
where T : class,new()
{
if (source == null)
return; if (target == null)
{
target = new T();
} foreach (var property in target.GetType().GetProperties())
{
var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null);
if (propertyValue != null)
{
if (propertyValue.GetType().IsClass)
{ }
target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
} } foreach (var field in target.GetType().GetFields())
{
var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
if (fieldValue != null)
{
target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue });
}
}
}
}

调用方式

static void main(string[] args)
{
A a = new A();
a.Name = "aa";
a.Age = ;
B b = new B();
a.CopyTo(b);
}