在哪里初始化另一个 class

Where to initialize collection of another class

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

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 cars = new CarCollection("database");
List<Car> carDetails = new List<Car>();
foreach (int carID in cars)
{
    Car c = new Car(carID);
    c.PopulateAllCarInfo();
    carDetails.Add(c);
}

我是团队的新手,我将重构它以了解代码库。填充汽车集合的最佳方式是什么?单独的 class 是否矫枉过正?

我正在考虑尝试创建一个新的 CarCollection 来...

public CarCollection
{
    // This method would populate the info for all cars
    public List<Car> RetrieveCars("database") {}

    // Leave this so I can still retrieve only Car data for single cars if I want
    public List<int> ListCarIDs() {}
}

并将只访问一辆车的方法移动到Car

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

问题:CarCollection class 是否矫枉过正?您将检索集合的方法放在哪里? (注意我们没有使用 MVC 或任何其他模式)

我确实找到了这个,但它没有关于如何检索完整集合的任何建议:https://softwareengineering.stackexchange.com/questions/196125/is-it-a-good-practice-to-create-a-classcollection-of-another-class

What's the best way to populate a collection of Cars?

类 不应从数据源填充他们自己的数据 - 最坏的情况是将您的 class 绑定到特定数据源,最好的情况是添加对 的弱依赖性一些 数据源。

通常 class 例如 存储库 负责从源加载数据,并使用该数据创建对象,使用对象的构造函数或 public属性。

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

Is the CarCollection class overkill?

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

在我看来,您的项目正在使用 Active Record 模式,其中每个 class 都是到数据库存储中 table 的映射。如果这是真的,您的问题的答案将是:

What's the best way to populate a collection of Cars?

我会在您的 Car 中定义一个静态函数 class 来检索 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();

专业版:所有对汽车数据库的查询都集中在一个地方。

缺点:1)如果需要查询与Car有关系的不同table的字段,会增加复杂度。 2) 您的 class 将与数据库实现捆绑在一起,这会降低代码的可扩展性,就像@(D Stanley) 提到的那样。