我想在LINQ中做相同的以下内容,但我无法弄清楚如何:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
Run Code Online (Sandbox Code Playgroud)
什么是真正的语法?
string [] files = new string[2];
files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml";
files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml";
//Resharper complains this is an "access to modified closure"
for (int i = 0; i < files.Length; i++ )
{
// Resharper disable AccessToModifiedClosure
if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(),
delegate(string name) { return name.Equals(files[i]); }))
return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]);
// ReSharper restore AccessToModifiedClosure
}
Run Code Online (Sandbox Code Playgroud)
虽然ReSharper抱怨这是"访问修改后的闭包",但上述情况似乎工作正常.任何人都可以阐明这一点吗?
(这个主题在这里继续)
我希望有人可以向我解释在这段代码中会发生什么坏事,这会导致ReSharper给出"访问修改后的封闭"警告:
bool result = true;
foreach (string key in keys.TakeWhile(key => result))
{
result = result && ContainsKey(key);
}
return result;
Run Code Online (Sandbox Code Playgroud)
即使上面的代码看起来很安全,在其他"修改后的闭包"实例中会发生什么坏事?我经常在使用LINQ查询时看到这个警告,我倾向于忽略它,因为我不知道会出现什么问题.ReSharper尝试通过创建对我来说毫无意义的第二个变量来解决问题,例如它将foreach上面的行更改为:
bool result1 = result;
foreach (string key in keys.TakeWhile(key => result1))
Run Code Online (Sandbox Code Playgroud)
更新:在附注中,显然整个代码块可以转换为以下语句,这不会导致修改后的闭包警告:
return keys.Aggregate(
true,
(current, key) => current && ContainsKey(key)
);
Run Code Online (Sandbox Code Playgroud) resharper让我把它变成一个局部变量,写下"访问修改后的闭包"
if (filter != null)
{
if (filter.CityId != 0)
{
ads = ads.Where(x => x.Ad.CityId == filter.CityId);
}
if (filter.BusinesCategoryId != 0)
{
ads = ads.Where(x => x.BusinessCategoryId == filter.BusinesCategoryId);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么局部变量过滤?