C# 在何处初始化另一个类的集合

C# 在何处初始化另一个类的集合,c#,winforms,class-design,C#,Winforms,Class Design,初始化对象集合的最佳位置在哪里?我开始从事一个以前对数据库调用非常敏感的老项目。。。所以我们有这样的东西: public class Car { public int ID { get; set; } public string Make { get; set; } public Car(int id) {} public void AddCar() {} public void EditCar() {} public void Populat

初始化对象集合的最佳位置在哪里?我开始从事一个以前对数据库调用非常敏感的老项目。。。所以我们有这样的东西:

public class Car
{
    public int ID { get; set; }
    public string Make { get; set; }

    public Car(int id) {}

    public void AddCar() {}
    public void EditCar() {}
    public void PopulateAllCarInfo() {}
}

public class CarCollection : IEnumerable
{
    public int this[int index] { get return CarIDs[index - 1] }

    public CarCollection(string database)() // Populates CarIDs

    public List<int> CarIDs;

    public Car GetCarByID(int id){
        Car c = new Car(id);
        c.PopulateAllCarInfo();
        return c;    
    }
}
问题:CarCollection类是否有过多的杀伤力?您将检索集合的方法放在哪里?(注意,我们没有使用MVC或任何其他模式)

我确实找到了这个,但它没有任何关于如何检索完整集合的建议:

填充汽车集合的最佳方式是什么

类不应该从数据源填充自己的数据——最坏的情况是将类与特定数据源绑定,最好的情况是向某些数据源添加弱依赖

通常,存储库之类的类负责从源加载数据,并使用该数据创建对象,使用对象的构造函数或公共属性

因此,在您的情况下,一个好的设计是创建一个
CarRepository
,它可以通过从源加载数据来创建
Car
s的集合,并将任何更改保存回源

CarCollection类是否过火了


是-当您只需要迭代集合(而不是添加到集合中)时,您应该能够使用
List
作为具体类型和
IEnumerable
。您当然不应该实现非泛型的
IEnumerable
,因为在枚举集合时会丢失类型安全性。

在我看来,您的项目正在使用活动记录模式,其中每个类都是到数据库存储中表的映射。如果这是真的,你的问题的答案是:

填充汽车集合的最佳方式是什么

我将在Car类中定义一个静态函数来检索Car的集合。例如:

public class Car
{
    //.....

    public static IEnumerable<Car> FetchAll() 
    { 
        // code to retrieve all car will be put here
    }
    public static Car FetchOne(int carID)
    {
        // code to retrieve one car will be put here
    }
    public static Car FetchBy(string make, int year )
    {
        // further codes to retrieve car by conditions can be put here
    }
    // and so on....
}
公车
{
//.....
公共静态IEnumerable FetchAll()
{ 
//检索所有汽车的代码将放在这里
}
公共静态车取一(int carID)
{
//检索一辆车的代码将放在这里
}
公共静态车辆取款(字符串品牌,整数年)
{
//根据条件检索汽车的更多代码可以放在这里
}
//等等。。。。
}
在实现代码中,您可以按如下方式使用:

IEnumerable<Car> allCar = Car.FetchAll();
IEnumerable allCar=Car.FetchAll();
赞成:所有对汽车数据库的查询都在一个地方

缺点:1)如果需要从与Car有关系的不同表中查询字段,则会增加复杂性。2) 您的类将与数据库实现联系在一起,这会降低代码的可扩展性,如@(D Stanley)所述

public Car
{
    public Car GetCarByID(int id) {} // Populate Car
}
public class Car
{
    //.....

    public static IEnumerable<Car> FetchAll() 
    { 
        // code to retrieve all car will be put here
    }
    public static Car FetchOne(int carID)
    {
        // code to retrieve one car will be put here
    }
    public static Car FetchBy(string make, int year )
    {
        // further codes to retrieve car by conditions can be put here
    }
    // and so on....
}
IEnumerable<Car> allCar = Car.FetchAll();