解析通用类型而不在接口上指定它 [英] Resolve a generic type without specifying it on the interface

查看:31
本文介绍了解析通用类型而不在接口上指定它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下层次的接口:

I have the following hierarchy of interfaces:

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

在我的存储库层中,我有一个当前定义为的 GetOne 方法:

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) { ... }
}

我想将存储库中的参数约束为实体的通用接口指定的 TKey 类型.显而易见的解决方案是:

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) { ... }
} 

这可行,但要求我在创建存储库或通过接口注入时明确指定TKey.我想做的是这样的事情(不过下面的代码将不起作用):

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

是否可以将TKey约束为IEntity的通用参数,而无需在类上指定它?如果是这样,我该怎么办?

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?

推荐答案

对我来说,无需传递 TEntity Tkey 就能获得的距离越近,

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.

有了接口继承,您只需返回 TEntity 而不是 IEntity< TKey> .

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

这篇关于解析通用类型而不在接口上指定它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆