所以我正在从一本书中实现一个项目,我有点困惑为什么我需要这些lambdas.
public class Cart
{
private List<CartLine> lineCollection = new List<CartLine>();
public class CartLine
{
public Product Product { get; set; }
public int Quantity { get; set; }
}
public void RemoveLine(Product product)
{
lineCollection
.RemoveAll(p => p.Product.ProductID == product.ProductID);
}
}
Run Code Online (Sandbox Code Playgroud)
我为什么需要.RemoveAll(p=> p.Product.ProductID == product.ProductID)?它只.RemoveAll需要处理lambda表达式吗?我不知道为什么我不能使用this.Product.ProductID,我意识到Product是一个列表,p=> P.Product正在进行某种迭代并比较值直到它找到它需要的东西?
产品定义于
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我常常对Lambdas在这些事情上的目的感到困惑.是否有一些平等,p=>p.Product.ProductID == product.ProductID
我可以看到不使用Lambdas所以我可以更多地了解它是什么简写?
我似乎无法绕过这一个,并提前感谢.
它们是代表的简写.在您的情况下,没有lambdas的相同代码将如下所示:
public void RemoveLine( Product product )
{
var helper = new RemoveAllHelper();
helper.product = product;
lineCollection.RemoveAll( helper.TheMethod );
}
class RemoveAllHelper
{
public Product product;
public bool TheMethod( CartLine p ) { return p.Product.ProductID == product.ProductID; }
}
Run Code Online (Sandbox Code Playgroud)
因为lambda包含一个在lambda之外定义的变量(称为"bound"或"capture"变量),所以编译器必须创建一个带有字段的辅助对象来放入该变量.
对于没有绑定变量的lambda,可以使用静态方法:
public void RemoveLine( Product product )
{
lineCollection.RemoveAll( TheMethod );
}
public static bool TheMethod( CartLine p ) { return p.Product.ProductID == 5; }
Run Code Online (Sandbox Code Playgroud)
当唯一的绑定变量是this,则可以使用同一对象上的实例方法:
public void RemoveLine( Product product )
{
lineCollection.RemoveAll( this.TheMethod );
}
public bool TheMethod( CartLine p ) { return p.Product.ProductID == this.targetProductID; }
Run Code Online (Sandbox Code Playgroud)