2011-01-08 145 views
1

我再次抱歉,我的第一個問題的這個問題繼續: 考慮這個接口:從泛型方法返回類型

interface IRepository<T,U> where T:class where U:class 
{ 
    IEnumerable<U> SelectAll(); 

    bool Insert(T item); 

    IEnumerable<T> FindAll(Func<T, bool> exp); 
} 

,我實現此接口:

public class Repository : IRepository<Customer,Select4ColumnsOfCustomers> 
{ 

    #region IRepository<Customer,Select4ColumnsOfCustomers> Members 

    public IEnumerable<Select4ColumnsOfCustomers> SelectAll() 
    { 
     throw new NotImplementedException(); 
    } 

    public bool Insert(Customer item) 
    { 
     throw new NotImplementedException(); 
    } 

    public IEnumerable<Customer> FindAll(Func<Customer, bool> exp) 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 

public class Select4ColumnsOfCustomers 
{ 
    public int CustomerID { get; set; } 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string Phone { get; set; } 
} 

我想在northwind數據庫中只返回Customer列的4列。 Ok.this工作,但如果我想補充一點,返回其他類型的其他方法,我必須聲明S,U,M,W,...在接口和實現它,我必須寫這樣的代碼:

public class Repository : IRepository<Customer,RetType1,RetType2,RetType3,....> 

這不是good.what是另類的this.Is它可能對於返回類型寫入變種?還是爲了返回類型的佔位符? 感謝

+0

建議使用`Datatable`或這種事情的ORM。 – nan 2011-01-08 18:58:57

回答

3

您的倉庫可以實現多個接口。

public class Repository : IRepository<TResult1, T1>, IRepository<Tresult2, T2>, etc... 

你全選方法將需要的通用像

TResult SelectAll<TResult>(); 

但是安傑是正確的,可以考慮使用ORM,這樣就可以概括這個代碼。退房NHiberanteEntity Framework

+0

你能告訴我一個EF例子嗎? – Arian 2011-01-08 19:18:44