我正在寻找关于为什么允许编译以下代码行的解释:
var results = someCollection.Where(x => x.SomeBooleanProperty = true);
注意使用单个相等运算符(可能开发人员处于 SQL 模式),这是一个很容易犯的错误。这会编译并在评估结果时(例如someCollection.ToList()
)将整个集合上的标志更改为 true!
如果您正在使用实体框架或任何其他 ORM,那么这可能会被检测为更改。我刚刚在生产代码中遇到了这个问题,但幸运的是它只是在只读屏幕上引起了一个小问题(但完全令人困惑)。试想一下,如果数据实际上是持久的,那么可能会导致可怕的逻辑和数据问题。
只是为了确保我没有发疯并且它确实改变了我编写的测试失败的数据:
[Test]
public void Test_because_im_scared()
{
var falseProperty = new TestModel {BooleanProperty = false};
var trueProperty = new TestModel {BooleanProperty = true};
var list = new List<TestModel>{falseProperty, trueProperty};
var results = list.Where(x => x.BooleanProperty = true);
Assert.IsFalse(falseProperty.BooleanProperty);
Assert.IsTrue(trueProperty.BooleanProperty);
//all fine so far, now evaluate the results
var evaluatedResults = results.ToList();
Assert.IsFalse(falseProperty.BooleanProperty); //test fails here!
Assert.IsTrue(trueProperty.BooleanProperty);
}