2011-01-08 146 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