开发者

Return type from generic methods

开发者 https://www.devze.com 2023-02-03 09:38 出处:网络
I\'m Sorry again but this question continuance of my first question: consider this Interface: interface IRepository<T,U> where T:class where U:class

I'm Sorry again but this question continuance of my first question: consider this Interface:

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

    bool Insert(T item);

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

and I Implement this interface:

 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; }
}

I want to return just 4 column of Customer table in northwind database. Ok.this work but if I want to add other method that return other types I must declare S,U,M,W,... in Interface and in Implement of it I must write this Code:

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

this not good.what is alternative for this.Is it 开发者_JS百科possible that write var for Return Types?Or a place holder for return types? thanks


Your repository can implement multiple interfaces.

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

Your SelectAll method will need to be generic like

TResult SelectAll<TResult>();

However Andrzej is right, consider using an ORM so that you can generalize this code. Check out NHiberante and Entity Framework.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号