我有两个相同类型的对象,需要将一个对象的属性值复制到另一个对象。有两种选择:
- 使用反射,遍历第一个对象的属性并复制值。
- 对第一个对象进行序列化,然后反序列化出一个副本。
class Person
{
public int ID { get; set; }
public string Firsthand { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public decimal Weight { get; set; }
}
需要将Person p1
的属性值复制到Person p2
中。
针对这个简单的示例,哪种方法更快?
更新
对于序列化,我使用了此处建议的ObjectCopier进行深度克隆。
对于反射,我使用以下代码:
foreach (PropertyInfo sourcePropertyInfo in copyFromObject.GetType().GetProperties())
{
PropertyInfo destPropertyInfo = copyToObject.GetType().GetProperty(sourcePropertyInfo.Name);
destPropertyInfo.SetValue(
copyToObject,
sourcePropertyInfo.GetValue(copyFromObject, null),
null);
}