我陷入了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;
}
}
Product是一个简单的类,拥有一些字段如名称、价格等。我有很多疑问。首先,我不明白C#如何知道MyExtensionMethods是ShoppingCart的扩展,然后我也不明白TotalPrices如何知道prod来自ShoppingCart类中的Products。能否有人简要地解释一下这几行代码背后的逻辑呢?
谢谢大家,抱歉我的问题有点愚蠢。
TotalPrices
是IEnumerable<Product>
的扩展方法,ShoppingCart
实现了这个接口。 - Pavel Anikhouski