0
我已經接口下面的層級:解析的通用型不指定它的接口上
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:IRepository where TEntity:IEntity '? –
ColinM
@ColinM我可以將方法定義爲'GetOne(string)'然後。關鍵是鍵可能是一個int,一個字符串,一個long或者一個複合對象。 –