如何在C#中创建通用的Clone工厂方法?

Edw*_*uay 1 c# generics

我有以下课程:

public abstract class Item
{
    //...
}

public class Customer : Item
{
    //...
}

public class Address : Item
{      
    //...
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使用这样的自定义反射类创建精确的克隆:

Customer customer = new Customer();
ItemReflector irCustomer = new ItemReflector(customer);
Customer customerClone = irCustomer.GetClone<Customer>();
Run Code Online (Sandbox Code Playgroud)

但我遇到了GetClone方法的语法问题:

public class ItemReflector
{
    private Item item;

    public ItemReflector(Item item)
    {
        this.item = item;
    }

    public Item GetClone<T>()
    {
        T clonedItem = new T();
        //...manipulate the clonedItem with reflection...
        return clonedItem;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有什么需要更改为上面的GetClone()方法,以便它可以工作?

Dar*_*rov 6

new如果您希望能够实例化,则需要约束T:

public Item GetClone<T>() where T: new()
{
    T clonedItem = new T();
    //...manipulate the clonedItem with reflection...
    return clonedItem;
}
Run Code Online (Sandbox Code Playgroud)