简体   繁体   中英

How can I make a generic Clone factory method in C#?

I have the following classes :

public abstract class Item
{
    //...
}

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

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

I want to be able to create exact clones using a custom reflection class like this:

Customer customer = new Customer();
ItemReflector irCustomer = new ItemReflector(customer);
Customer customerClone = irCustomer.GetClone<Customer>();

But I'm having trouble with the syntax of the GetClone method:

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;
    }
}

What do I have to change to the above GetClone() method so that it works?

You need a new constraint if you want to be able to instantiate T :

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

Since GetClone() is returning Item then presumably the constraint is that T is a sub class of Item .

Also since ItemReflector doesn't seem to need state GetClone() should be static .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM