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

26
我是一个有用的助手,可以翻译文本。
我正在构建一个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;
    }

5
在Sortcarboot中的每个CarBootSaleList c上循环。 - Phil
你可以在这里找到答案(foreach的实现):https://dev59.com/-Wgu5IYBdhLWcg3w_L7J#14812801 - polkduran
这两行代码有关联吗?List<CarBootSaleList> Sortcarboot = new List<CarBootSaleList>();foreach (CarBootSale c in carBootSaleList) - bash.d
carBootSaleList 变量在哪里声明的? - Marcus Vinicius
这个问题已经有答案了吗,请问 @Danny? - sanepete
显示剩余2条评论
4个回答

22
你的 CarBootSaleList 类并不是一个列表,而是一个包含列表的类。
你有三个选择:
使你的 CarBootSaleList 对象实现 IEnumerable 或者
让你的 CarBootSaleList 继承自 List<CarBootSale> 或者
如果你很懒,几乎可以在不编写额外代码的情况下完成相同的事情。
List<List<CarBootSale>>

8
你真的建议作者使用包含CarBootSales列表的List吗?只有前两个选项是实际可行的。 - Security Hound

18
你没有展示给我们carBootSaleList的声明。然而从异常信息中我可以看到它是CarBootSaleList类型。这个类型没有实现IEnumerable接口,因此不能在foreach中使用。
你的CarBootSaleList类应该实现IEnumerable<CarBootSale>
public class CarBootSaleList : IEnumerable<CarBootSale>
{
    private List<CarBootSale> carbootsales;

    ...

    public IEnumerator<CarBootSale> GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }
}

5

foreach循环中,使用carBootSaleList.data而不是carBootSaleList

你可能不再需要答案,但这可能会帮助其他人。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接