如何克隆具有已设置的所有值的类?

JC *_*ard 3 .net c#

类示例:

public class Customer
{
    public int CustomerID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用班级:

    Customer customer1 = new Customer();
    customer1.CustomerID = 1;
Run Code Online (Sandbox Code Playgroud)

现在,我如何创建一个customer2类,其中包含存储在customer1中的所有值?

Mar*_*zek 6

你可以手动完成:

var customer2 = new Customer { CustomerID = customer1.CustomerID };
Run Code Online (Sandbox Code Playgroud)

您可以ICloneableCustomer类中实现接口:

public class Customer : ICloneable
{
    private int CustomerID { get; set; }

    public Customer Clone()
    {
        return new Customer { CustomerID = this.CustomerID };
    }

    object ICloneable.Clone()
    {
        return this.Clone();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

var customer2 = customer1.Clone();
Run Code Online (Sandbox Code Playgroud)

您可以将对象序列化为XML/JSON,然后将其反序列化为新对象,如本答案中所述:在C#中深度克隆对象.

或者,您可以使用反射来获取并将所有属性/字段值复制到新Customer实例中.它可能会有糟糕的性能,但您必须对其进行测量以确定它有多糟糕.

编辑

还有一种方法:使用Expression Tree可以更快地制作反射版本!获取所有字段/属性并使用在运行时编译所有必要的分配Expression.Lambda.之后,每次下一次Clone调用都将使用已编译的代码,因此根本没有性能缺陷.我已经Clone<T>使用Expression类,静态构造函数和反射创建了扩展方法.您可以在CodePlex上找到代码:CloneExtension.cs