【问题标题】:Resolve a generic type without specifying it on the interface解析泛型类型而不在接口上指定它
【发布时间】:2016-11-26 00:14:18
【问题描述】:

我有以下接口层次结构:

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

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

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

我想将存储库上的参数限制为实体的通用接口指定的TKey 类型。显而易见的解决方案是:

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

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

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

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

【问题讨论】:

  • public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : IEntity&lt;string&gt; ?
  • @ColinM 那么我也可以将方法定义为GetOne(string)。关键是键可能是 int、string、long 甚至是复合对象。

标签: c# generics


【解决方案1】:

在不经过TEntityTkey的情况下越接近,对我来说是:

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

我以后可能会考虑其他事情,但就目前而言,我认为如果不传递两个通用参数,您将无法做到。

使用接口继承,您可以只返回一个TEntity 而不是IEntity&lt;TKey&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2020-08-03
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多