复制对象有两种类型。
- 参考副本
- 价值副本
要通过引用复制对象,只需使用“=”运算符即可。
e.g:
var o1 = new ClassClass();
var o2 = o1;
按值复制对象有多种方法,例如:
通过构造函数复制(如您所写)
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Student(Student std)
{
FirstName = std.FirstName;
LastName = std.LastName;
}
}
创建一个辅助类,将 s1 作为输入传递,并返回 s2 作为
结果
static void Main(string[] args)
{
var s1 = new Student();
var s2 = ClassHelper.CopyObject(s1);
}
public static class ClassHelper
{
public static Student CopyObject(Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
通用复制对象(使用反射)
private static void CopyClass<T>(T copyFrom, T copyTo, bool copyChildren)
{
if (copyFrom == null || copyTo == null)
throw new Exception("Must not specify null parameters");
var properties = copyFrom.GetType().GetProperties();
foreach (var p in properties.Where(prop => prop.CanRead && prop.CanWrite))
{
if (p.PropertyType.IsClass && p.PropertyType != typeof(string))
{
if (!copyChildren) continue;
var destinationClass = Activator.CreateInstance(p.PropertyType);
object copyValue = p.GetValue(copyFrom);
CopyClass(copyValue, destinationClass, copyChildren);
p.SetValue(copyTo, destinationClass);
}
else
{
object copyValue = p.GetValue(copyFrom);
p.SetValue(copyTo, copyValue);
}
}
}
为这个类编写一个扩展方法,我建议这样做。
public static class ExtensionClass
{
public static Student CopyAsNewObject(this Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
static void Main(string[] args)
{
var s1 = new Student();
var s2 = s1.CopyAsNewObject();
}