2009-12-15 45 views
1

我有以下如何在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()方法才能使用它?

+0

看看我的答案[爲什麼沒有ICloneable ?](http://stackoverflow.com/questions/536349/why-no-icloneablet) – TcKs 2009-12-15 11:10:38

回答

6

你需要一個new約束,如果你希望能夠實例T

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

完美,謝謝。 – 2009-12-15 10:59:32

0

由於GetClone()正在恢復Item那麼想必約束是T是一個子類的Item

也因爲ItemReflector似乎並不需要狀態GetClone()應該是static