[英]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
因此約束可能是T
是Item
的子類。
另外,由於ItemReflector
似乎不需要狀態,因此GetClone()
應該為static
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.