LINQ查询中的C#lambda表达式
问题描述:
我知道,如果使用局部变量,循环内的lambda表达式会导致问题。 (见http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx)LINQ查询中的C#lambda表达式
现在我有一个情况,在那里我使用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();
这是安全的呢?编译器是否总是正确地扩展这个表达式并确保“产品”指向正确的对象?
答
是的,它是安全的。您的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
变量。