Resolve a generic type without specifying it on the interface

╄→гoц情女王★ 提交于 2021-02-17 05:30:10

问题


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?


回答1:


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>.



来源:https://stackoverflow.com/questions/40813725/resolve-a-generic-type-without-specifying-it-on-the-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!