using System;
using System.Reflection;
public static class PropertyCopier
{
/// <summary>
/// 将源对象的值复制到目标对象,只复制具有相同名称的属性值。
/// </summary>
/// <typeparam name="T1">目标对象的类型</typeparam>
/// <typeparam name="T2">源对象的类型</typeparam>
/// <param name="destination">目标对象</param>
/// <param name="source">源对象</param>
public static void CopyProperties<T1, T2>(T1 destination, T2 source)
where T1 : class
where T2 : class
{
if (destination == null) throw new ArgumentNullException(nameof(destination));
if (source == null) throw new ArgumentNullException(nameof(source));
Type sourceType = source.GetType();
Type destinationType = destination.GetType();
PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo sourceProperty in sourceProperties)
{
PropertyInfo destinationProperty = destinationType.GetProperty(sourceProperty.Name, BindingFlags.Public | BindingFlags.Instance);
if (destinationProperty != null && destinationProperty.CanWrite)
{
object value = sourceProperty.GetValue(source);
destinationProperty.SetValue(destination, value);
}
}
}
}
// 示例实体类
public class Entity1
{
public int Id { get; set; }
public string Name { get; set; }
public double Value { get; set; }
}
public class Entity2
{
public int Id { get; set; }
public string Name { get; set; }
public double Value { get; set; }
public string AdditionalProperty { get; set; }
}
// 测试代码
public class Program
{
public static void Main()
{
Entity2 entity2 = new Entity2
{
Id = 1,
Name = "Entity2",
Value = 100.0,
AdditionalProperty = "This is Entity2"
};
Entity1 entity1 = new Entity1();
PropertyCopier.CopyProperties(entity1, entity2);
Console.WriteLine($"Entity1 Id: {entity1.Id}");
Console.WriteLine($"Entity1 Name: {entity1.Name}");
Console.WriteLine($"Entity1 Value: {entity1.Value}");
}
}