简体   繁体   中英

Generics - Passing instances as a base type

I'm currently working on the Data Access Layer for our new application, it's not a large application so I've decided to go with a Dao pattern, converting each Model item into a Dao Item before storing it to the database through stored queries.

With as much as possible of this I've used generic interfaces and abstract classes to remove the repetitive operations but now I've hit a bit of a road block.

What we have is an Interface for Dao Conversion classes looking like the following:

internal interface IDaoConverter<TModel, TDao>
    where TModel : ModelItem
    where TDao : DaoItem
{
    ToDao(TModel inModel);
    inDao);
}

This works fine so far and fits it's function, you specify the Model type and the Dao type it will be converted into (1-1 relationship) in the class definition and the functions are created to match these types. Instances of these Dao Converters are held in a factory to make the retrieval easier.

The next thing I want is to create Data Access classes that will use this and I want to design this in a Generic way.

What I'm after is a way to ask the Dao Converter Factory that I want a Dao Converter that can handle a specific type of Model item but so far I can't find a way to specify this.

public abstract class AbstractDataAccess<T> where T: ModelItem
{
    protected IDaoConverter<T,?> Converter;

    public void Init(IDaoConverter<T,?> inConverter)
    {
        Converter = inConverter;
    }
}

I basically want to be able to replace the Question Marks with whatever type I want within the class. I'm currently having to write each Data Access class out completely due to this.

如果在初始化时提供了转换器,则可以使方法访问DaoConverter抽象,并派生一个(可能是抽象的)类,该类具有表示Dao-Type的第二个类型参数。

public abstract class AbstractDataAccess<T, TDao> : AbstractDataAccess<T> where ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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