当我们需要一个临时变量的时候 使用赋值的方式去创建临时对象,更改了对象的指向,临时变量仍然会跟随对象源数据发生更改,这个时候我们就需要使用一个方法,来将源对象中的所有数据复制给临时变量,通过以下方法可是实现对对象的复制
1. 首先,通过获取源对象 `source` 和目标对象 `destination` 的类型信息,分别通过 `source.GetType()` 和 `destination.GetType()` 来获取它们的属性信息。
2. 然后,遍历源对象的属性集合,在每一次循环中,首先判断是否目标对象中存在与源对象相同名称和类型的属性。这一步主要通过 LINQ 查询进行实现,即 `destinationProperties.FirstOrDefault(p => p.Name == sourceProperty.Name && p.PropertyType == sourceProperty.PropertyType)`。
3. 如果目标对象存在对应的属性,并且该属性可写,就可以使用 `sourceProperty.GetValue(source)` 获取源对象属性的值,然后通过 `destinationProperty.SetValue(destination, value)` 将该值赋给目标对象的属性。
public static class Extensions
{
public static void CopyFrom(this object destination, object source)
{
PropertyInfo[] sourceProperties = source.GetType().GetProperties();
PropertyInfo[] destinationProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in sourceProperties)
{
var destinationProperty = destinationProperties.FirstOrDefault(p => p.Name == sourceProperty.Name
&& p.PropertyType == sourceProperty.PropertyType);
if (destinationProperty != null && destinationProperty.CanWrite)
{
object value = sourceProperty.GetValue(source);
destinationProperty.SetValue(destination, value);
}
}
}
}