C# Foreach statement does not contain public definition for GetEnumerator

后端 未结 4 1578
孤街浪徒
孤街浪徒 2021-02-07 00:33

I\'m having a problem with a Windows Form application I\'m building in C#. The error is stating \"foreach statement cannot operate on variables of type \'CarBootSale.CarBootSale

相关标签:
4条回答
  • 2021-02-07 00:44

    You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

    http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

    But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

    http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

    Your code also seems a bit strange, like you are nesting lists?

    0 讨论(0)
  • 2021-02-07 00:48

    In foreach loop instead of carBootSaleList use carBootSaleList.data.

    You probably do not need answer anymore, but it could help someone.

    0 讨论(0)
  • 2021-02-07 00:49

    You don't show us the declaration of carBootSaleList. However from the exception message I can see that it is of type CarBootSaleList. This type doesn't implement the IEnumerable interface and therefore cannot be used in a foreach.

    Your CarBootSaleList class should implement IEnumerable<CarBootSale>:

    public class CarBootSaleList : IEnumerable<CarBootSale>
    {
        private List<CarBootSale> carbootsales;
    
        ...
    
        public IEnumerator<CarBootSale> GetEnumerator()
        {
            return carbootsales.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return carbootsales.GetEnumerator();
        }
    }
    
    0 讨论(0)
  • 2021-02-07 01:01

    Your CarBootSaleList class is not a list. It is a class that contain a list.

    You have three options:

    Make your CarBootSaleList object implement IEnumerable

    or

    make your CarBootSaleList inherit from List<CarBootSale>

    or

    if you are lazy this could almost do the same thing without extra coding

    List<List<CarBootSale>>
    
    0 讨论(0)
提交回复
热议问题