从foreach转换为for

时间:2018-11-07 11:14:17

标签: c#

已经尝试进行转换,仍然出现错误。。非常感谢您的收看,但希望有人能为您提供帮助。还能帮助我修复其他方法

static void PrintHighestHallmark(JeweleryContainer shops)
{
    foreach(JeweleryContainer s in shops)
    {
        int count = s.earring.Count + s.necklace.Count + s.ring.Count;
        Console.WriteLine("Parduotuveje " + s.Name + " yra " + count + " auksciausios prabos gaminiai(iu).");
    }
}

1 个答案:

答案 0 :(得分:0)

鉴于您当前的代码,仅此而已,我们可以看到,但是正如我所说,这可能行得通,不知道JeweleryContainer的样子会妨碍我们根据您的真实目标更好地回答对我们来说还不太清楚。

static void PrintHighestHallmark(JeweleryContainer shops)
{
    int count = shops.earring.Count + shops.necklace.Count + shops.ring.Count;
    Console.WriteLine("Parduotuveje " + shops.Name + " yra " + count + " auksciausios prabos gaminiai(iu).");
}

现在,如果目标是创建某种类型的集合的迭代器,则从这里开始:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators

使用容器列表吗?

static void PrintHighestHallmark(List<JeweleryContainer> shops)
{
    foreach(JeweleryContainer s in shops)
    {
        int count = s.earring.Count + s.necklace.Count + s.ring.Count;
        Console.WriteLine("Parduotuveje " + s.Name + " yra " + count + " auksciausios prabos gaminiai(iu).");
    }
}

使用for循环:

static void PrintHighestHallmark(List<JeweleryContainer> shops)
{
    for (var i = 0; i < shops.Count; i++) {
        int count = shops[i].earring.Count + shops[i].necklace.Count + shops[i].ring.Count;
        Console.WriteLine("Parduotuveje " + shops[i].Name + " yra " + count + " auksciausios prabos gaminiai(iu).");
    }
}