有关C#中自定义集合的问题

Rag*_*hav 4 c# design-patterns

我想知道从自定义集合类返回对象时最好的模式是什么.为了说明我的问题,这是一个例子:

我有一个Customer类:

public class Customer
{
   //properties
   //methods
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个客户集合类:

public class Customercollection: Collection<Customer>
{

  public Collection<Customer> FindCustomers()
   {
     //calls DAL and gets a Collection of customers
     Collection<Customer> customers = DAL.GetCustomers();

     return customers;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,此方法的替代版本可以是:

public class Customercollection: Collection<Customer>
{

  public Collection<Customer> FindCustomers()
   {
     //calls DAL and gets a Collection of customers
     Collection<Customer> customers = DAL.GetCustomers();
     foreach(Customer c in customers)
     this.Add(c);
     return this;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想讨论哪一个更好的方法?还有其他方法比两个以上的方法更好吗?

And*_*are 15

我建议采用第三种方法:

编辑: 我已更新此代码示例以反映下面的OP的评论.

public class Customer
{
    public static ICollection<Customer> FindCustomers()
    {
        Collection<Customer> customers = new Collection<Customer>();

        foreach (CustomerDTO dto in DAL.GetCustomers())
            customers.Add(new Customer(dto));  // Do what you need to to create the customer

        return customers;
    }
}
Run Code Online (Sandbox Code Playgroud)

大多数情况下不需要自定义集合 - 我假设这是其中一种情况.您还可以将实用程序方法添加到类型(在本例中为Customer类型),因为这有助于开发人员发现这些方法.(这一点更多的是品味问题 - 因为这是一种静态方法,你可以自由地将它放在你想要的任何类型中CustomerUtility或者CustomerHelper例如).

我的最终建议是返回一个接口类型,FindCustomers()以便将来为实现更改提供更大的灵活性.显然DAL.GetCustomers(),必须返回一些实现的类型,IList<T>但是任何API方法(特别是在数据层之类的不同层中)也应该返回接口类型.