简体   繁体   中英

Resolve a generic type without specifying it on the interface

I have the following hierarchy of interfaces:

public interface IEntity { object Key; }
public interface IEntity<TKey> { TKey TypedKey; }

In my repository layer, I have a GetOne method currently defined as such:

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : IEntity
{
    public TEntity GetOne(object key) { ... }
}

I would like to constrain the argument on the repository to the TKey type specified by the generic interface of the entity. The obvious solution would be:

public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
    where TEntity : IEntity<TKey>
{
    public TEntity GetOne(TKey key) { ... }
} 

This works, but requires me to specify the TKey explicitly when creating a repository, or injecting it via the interface. What I would like to do is something like this (the following code will not work, though):

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : IEntity
{
    public TEntity GetOne<TKey>(TKey key) where TEntity : IEntity<TKey> { ... }
}

Is it at all possible to constrain TKey to be the generic parameter of IEntity without specifying it on the class? If so, how would I do that?

The closer you can get without passing TEntity and Tkey , for me is:

public interface IEntity
{
    object Key { get; set; }
}

public interface IEntity<TKey> : IEntity
{
    TKey TypedKey { get; set; }
}

public class Repository<TEntity>
    where TEntity : IEntity
{
    public IEntity<TKey> GetOne<TKey>(TKey key)
    {
        ...;
    }
}

I may think about something else later, but for now, I don't think you can do it without passing both generic arguments.

With the interface inheritance, you could just return a TEntity instead of IEntity<TKey> .

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