我知道循环中的lambda表达式如果使用局部变量会导致问题。 (见http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx)
现在我有一种情况,我在LINQ查询中使用lambda表达式:
var products = from product in allProducts
select new
{
ID = product.ID,
Name = product.Name,
Content = new Func<object,string>(
(obj) => (GetSomeDynamicContent(obj, product))
)
};
someCustomWebControl.DataSource = products;
someCustomWebControl.DataBind();
这样做安全吗?编译器是否始终正确扩展此表达式并确保“product”指向正确的对象?
答案 0 :(得分:2)
是的,这样做是安全的。您的LINQ查询基本上扩展到:
private AnonType AnonMethod(Product product)
{
return new
{
ID = product.ID,
Name = product.Name,
Content = new Func<object,string>(
(obj) => (GetSomeDynamicContent(obj, product))
)
};
}
var products = allProducts.Select(AnonMethod);
someCustomWebControl.DataSource = products;
someCustomWebControl.DataBind();
如您所见,lambda表达式捕获allProducts中每个产品的product
变量。