public static void CopyProperties(object source, object destination)
{
var sourceProperties = source.GetType().GetProperties();
foreach (var prop in sourceProperties)
{
var destinationProperty = destination.GetType().GetProperty(prop.Name);
if (destinationProperty != null && destinationProperty.CanWrite && prop.CanRead)
{
destinationProperty.SetValue(destination, prop.GetValue(source));
}
}
}
// 使用
Person person1 = new Person { Name = "Alice", Age = 30 };
Person person2 = new Person();
CopyProperties(person1, person2);
|