gpt4 book ai didi

c# - 是否可以将泛型类型限制为接口(interface)、new()?

转载 作者:行者123 更新时间:2023-11-30 15:28:44 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的对象回收类

public class ObjectPool<T> where T : class, IRecyclable, new()
{
}

我希望能够在我的界面中使用它:

public interface ISomeInterface : IRecyclable
{
}

ObjectPool<ISomeInterface> pool = new ObjectPool<ISomeInterface>();

但这会产生错误:

error CS0310: The type `ISomeInterface' must have a public parameterless constructor in order to use it as parameter `T' in the generic type or method `ObjectPool<T>'

根据我在网上阅读的内容,我知道我不能在接口(interface)中指定构造函数。

我读到过您可以使用反射而不是“new”来创建新实例,尽管我担心执行此实例化的速度。

解决这种情况的正确方法是什么?有没有我完全忽略的更简单的解决方案?

最佳答案

接口(interface)只能实现其他接口(interface)。

interface IA : IB, IC
{
...
}

解决您的难题的一个好方法是同时引入工厂接口(interface)。

interface IThing
{
...
}

interface IThingFactory
{
IThing Create();
}

现在任何想要拥有创造事物能力的东西都应该为此目的接收一个 IThingFactory

如果你需要工厂的通用概念,你可以使用这样的东西:

interface IFactory<T>
{
T Create();
}

class ObjectPool<T, F>
where T : IRecyclable
where F : IFactory<T>
{
public ObjectPool(F factory)
{
...
}
}

关于c# - 是否可以将泛型类型限制为接口(interface)、new()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25162752/

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