【问题标题】:foreach statement cannot operate on variablesforeach 语句不能对变量进行操作
【发布时间】:2015-10-14 01:01:05
【问题描述】:

我必须上课,Custom Car Factory Class 和 Custom Car Factory,我正在尝试通过使用 foreach 来从定制汽车工厂注销 Custom Car 以获取工厂中的所有数据,但是我收到“foreach”错误语句不能对变量 CustomCarFactory 进行操作,因为 Custom 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

    }

}

【问题讨论】:

  • 您是不是要迭代 CarFactories 而不是 factory
  • 抱歉,是的。

标签: c# winforms


【解决方案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);
}

【讨论】:

  • 通过这种方式,我的界面只暴露了汽车品牌,无法暴露型号、序列号、车牌等值。
  • 是的,因为在我的 ICarFactory cs 中,公共接口 ICarFactory{ string CarName {get; }} 这就是为什么当我在 Car Factory 上使用 linq 时,我只能看到 x.CarName 而看不到我的内部字符串
猜你喜欢
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多