简体   繁体   English

使用泛型类和接口实现抽象工厂

[英]Implement abstract factory using generic class and interface

I want to implement an abstract factory (with singletons) and use it in my code with concrete instances of TType and TInterfaceType to be mapped to. 我想实现一个抽象工厂(带有单例)并在我的代码中使用它, TTypeTInterfaceType具体实例映射到。

Here is my current code: 这是我目前的代码:

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

I get an error: 我收到一个错误:

Cannot implicitly coonvert type TType to TInterfaceType 无法隐式将TType类型转换为TInterfaceType

How can I implement an abstract class with the method definition using a class and its corresponding interface. 如何使用类及其相应的接口实现方法定义的抽象类。 For example I want to use it as follows: 例如,我想使用它如下:

ConcreteFactory : AbstractFactory<ConcreteClass, IConcreteClass>

You need to add a constraint saying that TType must inherit from TInterfaceType : 您需要添加一个约束,说明TType必须从TInterfaceType继承:

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

Now the compiler knows that TType inherits from TInterfaceType and objectTtype is therefor assignable (and returnable) to TInterfaceType . 现在,编译器知道TType继承自TInterfaceTypeobjectTtype因此可分配(并且可返回)到TInterfaceType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM