gpt4 book ai didi

c# - 使用泛型类和接口(interface)实现抽象工厂

转载 作者:太空狗 更新时间:2023-10-30 01:29:43 26 4
gpt4 key购买 nike

我想实现一个抽象工厂(使用单例)并在我的代码中使用它,并将其映射到 TTypeTInterfaceType 的具体实例。

这是我当前的代码:

public abstract class AbstractFactory<TType, TInterfaceType> where TType : new() where TInterfaceType : class
{
private TInterfaceType objectTtype;
public TInterfaceType getInstance()
{
try
{
if (objectTtype == null)
{
objectTtype = new TType();
}

return objectTtype;
}
catch (Exception e)
{
throw e;
}
}
}

我得到一个错误:

Cannot implicitly coonvert type TType to TInterfaceType

如何使用类及其相应接口(interface)实现带有方法定义的抽象类。例如我想按如下方式使用它:

ConcreteFactory : AbstractFactory<ConcreteClass, IConcreteClass>

最佳答案

您需要添加一个约束,说明 TType 必须继承自 TInterfaceType:

public abstract class AbstractFactory<TType, TInterfaceType> 
where TType : TInterfaceType, new()
where TInterfaceType : class

现在编译器知道 TType 继承自 TInterfaceType 并且 objectTtype 因此可分配(和返回)给 TInterfaceType.

关于c# - 使用泛型类和接口(interface)实现抽象工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255343/

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