C#Foreach语句不包含GetEnumerator的公共定义

我正在C#中构建 Windows窗体应用程序的问题.错误是说“foreach语句不能对类型”CarBootSale.CarBootSaleList“的变量操作,因为”CarBootSale.CarBootSaleList“不包含”GetEnumerator“的公共定义.

我似乎不明白是什么原因造成的.

这是抛出错误的代码:

List<CarBootSaleList> Sortcarboot = new List<CarBootSaleList>();

        foreach (CarBootSale c in carBootSaleList)
        {
            if (c.Charity == "N/A")
            {
                Sortcarboot.Add(carBootSaleList);
                textReportGenerator.GenerateAllReport(Sortcarboot, AppData.CHARITY);
            }
        }

这是CarBootSaleList类,它表示没有GetEnumerator定义:

public class CarBootSaleList
{

    private List<CarBootSale> carbootsales;

    public CarBootSaleList()
    {
        carbootsales = new List<CarBootSale>();
    }

    public bool AddCarBootSale(CarBootSale carbootsale)
    {
        bool success = true;
        foreach (CarBootSale cbs in carbootsales)
        {
            if (cbs.ID == carbootsale.ID)
            {
                success = false;
            }
        }
        if (success)
        {
            carbootsales.Add(carbootsale);
        }
        return success;
    }

    public void DeleteCarBootSale(CarBootSale carbootsale)
    {
        carbootsales.Remove(carbootsale);
    }

    public int GetListSize()
    {
        return carbootsales.Count();
    }

    public List<CarBootSale> ReturnList()
    {
        return carbootsales;
    }

    public string Display()
    {
        string msg = "";

        foreach (CarBootSale cbs in carbootsales)
        {
            msg += String.Format("{0}  {1}", cbs.ID, cbs.Location, cbs.Date);
            msg += Environment.NewLine;
        }
        return msg;
    }
您的CarBootSaleList类不是列表.它是一个包含列表的类.

你有三个选择:

使您的CarBootSaleList对象实现IEnumerable

要么

使您的CarBootSaleList继承自List< CarBootSale>

要么

如果你是懒惰的,这几乎可以做同样的事情,没有额外的编码

List<List<CarBootSale>>
相关文章
相关标签/搜索