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

时间:2015-10-14 01:01:06

标签: c# winforms

我必须上课,自定义汽车工厂类和自定义汽车工厂,我试图从自定义汽车工厂取消注册自定义汽车,使用foreach获取工厂中的所有数据但是我收到错误的&# 34; foreach语句不能对变量操作CustomCarFactory因为Custom CarFactory不包含' GetEnumerator'的公共定义"

Custom Car Factory类

[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);

然后在这一部分中,我将从自定义工厂取消注册,但是我得到的#fore; foreach语句无法对varialbles进行操作CustomCarFactory因为Custom CarFactory不包含&#39; GetEnumerator&#39;的公共定义。 &#34;

   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

    }

}

1 个答案:

答案 0 :(得分:1)

您正在尝试迭代单个项而不是集合,这就是您收到该错误的原因。

您可以改为迭代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);
}