Foreach语句不能对变量进行操作

本文关键字:操作 变量 语句 不能 Foreach | 更新日期: 2023-09-27 18:17:38

我必须类,自定义汽车工厂类和自定义汽车工厂,我试图通过使用foreach来获取工厂中的所有数据,从自定义汽车工厂注销自定义汽车,但是我得到一个错误"foreach语句不能操作变量CustomCarFactory,因为自定义CarFactory不包含'GetEnumerator'的公共定义"

自定义汽车工厂类

[CustomCarFactory.cs]
internal class CustomCarFactory : ICarFactory
public CustomCarFactory(string make, string model, string serial, string plate)
    {
Make = make; 
Model = model;
Serial = serial;
Plate = plate;
}
internal string Make; 
internal string Model; 
internal string Serial; 
internal string Plate; 
Car Library Implementation class
[CarLibraryImplementation.cs]

internal static List<ICarFactory> CarFactories= new List<ICarFactory>(); 

在这一部分中,我将它注册到自定义工厂

private static CustomCarFactory factory = new CustomCarFactory(string.Empty, string.Empty, string.Empty, string.Empty);
 private static void registerCarImplementation(string make, string model, string serial, string plate)
        {
            factory = new CustomCarFactory(make, model, serial, plate);
                CarFactories.Add(factory);

然后在这一部分中,我将从自定义工厂注销它,但我得到"foreach语句不能操作变量CustomCarFactory,因为custom CarFactory不包含'GetEnumerator'的公共定义"

   private static void UnregisterCarImplementation(string make, string model, string serial, string plate)
                {
        foreach (var item in factory)
    {
// Get make from current factory
// Get model from current factory
    }
}

Foreach语句不能对变量进行操作

你正在尝试迭代单个项目而不是一个集合,这就是为什么你得到这个错误。

您可以遍历CarFactories集合:

private static void UnregisterCarImplementation(
    string make, string model, string serial, string plate)
{
    foreach (var item in CarFactories)
    {
        if (item.Make == make && item.Model == model
            && item.Serial == serial && item.Plate == plate)
        {
            // take some action
        }
    }
}

或者您可以使用集合可用的RemoveAll方法:

private static void UnregisterCarImplementation(
    string make, string model, string serial, string plate)
{
    CarFactories.RemoveAll(x => x.Make == make && x.Model == model
                                && x.Serial == serial && x.Plate == plate);
}