gpt4 book ai didi

c# - 如何在 C# 中制作通用的 Clone 工厂方法?

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:26 25 4
gpt4 key购买 nike

我有以下:

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

关于c# - 如何在 C# 中制作通用的 Clone 工厂方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1906532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com