与C和C ++不同,在C#中执行此操作
bool b = true;
if(b = false) Console.WriteLine("Dont panic!");
编译器(正确地)抱怨Warning CS0665 Assignment in conditional expression is always constant; did you mean to use == instead of = ?
但是,如果我不小心在Linq语句中分配而不是进行比较,则不会发出任何警告,并且编译器会编译:
var list = new List<bool>() { true, false, true };
var count = list.Count(b => b = false); //returns 0
Console.WriteLine(count);
反编译显示Lambda的外观:
internal bool <Main>b__0_0(bool b) => false;
使用对象时更糟:
var count = list.Count(s => s.SomeField = false); //returns 0
internal bool <Main>b__0_0(Program.Stuff s)
{
bool flag;
s.SomeField = flag = false;
return flag;
}
编译器是否有理由不阻止这种情况?