LINQ to SQL PredicateBuilder

∥☆過路亽.° 提交于 2019-12-03 12:25:19

Because PredicateBuilder is building up an expression which will be executed at a later point in time. When the compiler is generating the closure for the delegate, it finds any values which are created in the current scope, and carries them into the closure as well. Since InstrumentID is a value type (int), initializing and copying the value means each delegate/closure will carry that value with it. If you don't create a copy of the value each time, the expression will simply have a literal reference to f.InstrumentID, not to its underlying value. So later on, when the expression is actually executed, f.InstrumentID is evaluated and it will come out as whatever it was last set to, which is the last iteration.

Because it's not evaluating the condition, but simply building the expression. The expression binds to the variable defined in the foreach, which retains it's reference throughout the execution of the entire loop. Redefining it with a temporary variable forces each expression to use a different variable, which forces it to refer to the instance with the value at each iteration rather than having all iterations refer to the single reference and having the value of just the last iteration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!