了解IEnumerable-IEnumerator逻辑

问题描述 投票:0回答:1

我迷上了Adam Freeman的《 Asp net》一书,我读了很多有关IEnumerable和IEnumerator接口的书,但是仍然很难理解一些结果。我有这两节课。

public class ShoppingCart : IEnumerable<Product>
{
    public IEnumerable<Product> Products { get; set; }

    public IEnumerator<Product> GetEnumerator()
    {
        return Products.GetEnumerator();
    }

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

和第一个的扩展名,>>

 public static class MyExtensionMethods
{
    public static decimal TotalPrices (this IEnumerable<Product> products)
    {
        decimal total = 0;
        foreach (Product prod in products)
        {
            total += prod?.Price ?? 0;
        }
        return total;
    }
}

产品是一个简单的类,其中包括名称,价格等字段。我有很多疑问。首先,我不了解c#如何知道MyExtensionMethods是ShoppingCart的扩展,然后我不了解TotalPrices如何知道商品来自ShoppingCart类中的产品。有人可以简要解释一下这几行背后的逻辑吗?

谢谢大家,对不起这个问题。

我迷上了Adam Freeman的《 Asp net》一书,我读了很多有关IEnumerable和IEnumerator接口的书,但是仍然很难理解一些结果。我有这两节课。公共类...

c# ienumerable ienumerator
1个回答
0
投票

首先,我不了解c#如何知道MyExtensionMethods是ShoppingCart的扩展

© www.soinside.com 2019 - 2024. All rights reserved.