2016-11-26 19 views
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的泛型參數,而不指定它的類?如果是這樣,我該怎麼做?

+0

'public class Repository :IRepository where TEntity:IEntity '? – ColinM

+0

@ColinM我可以將方法定義爲'GetOne(string)'然後。關鍵是鍵可能是一個int,一個字符串,一個long或者一個複合對象。 –

回答

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