【发布时间】: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<TEntity> : IRepository<TEntity> where TEntity : IEntity<string>? -
@ColinM 那么我也可以将方法定义为
GetOne(string)。关键是键可能是 int、string、long 甚至是复合对象。