簡體   English   中英

如何在C#中創建通用的Clone工廠方法?

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

我有以下課程

public abstract class Item
{
    //...
}

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

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

我希望能夠使用這樣的自定義反射類創建精確的克隆

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

但是我在使用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;
    }
}

我必須更改上面的GetClone()方法才能起作用?

如果您希望能夠實例化T則需要一個new約束:

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

由於GetClone()返回Item因此約束可能是TItem的子類。

另外,由於ItemReflector似乎不需要狀態,因此GetClone()應該為static

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM