I have two samples of code. One works and returns the correct result, one throws a null reference exception. What's the difference? I know there's 开发者_如何学运维some magic happening with capturing variables for the lambda expression but I don't understand what's going on behind the scenes here.
int? x = null;
bool isXNull = !x.HasValue;
// this works
var result = from p in data.Program
where (isXNull)
select p;
return result.Tolist();
// this doesn't
var result2 = from p in data.Program
where (!x.HasValue)
select p;
return result2.ToList();
The first instance computes isXNull
based on the value x
had when the line bool isXNull = !x.HasValue;
is executed, while the second one uses the value of x
when return result2.ToList();
executes. It's not clear how you're getting a null reference exception, though, because I don't see any references.
I'm putting this down to a peculiarity with the way LLBLGen parses LINQ queries. I created a simple framework-only test scenario which doesn't have the same problem.
Seeing that you haven't told us what data.Program is, here is some code that I tried and it worked...in LINQPad.
var Program = new [] {"asd","asd"};
int? x = null;
bool isXNull = !x.HasValue;
// this works
var result = from p in Program
where (isXNull)
select p;
// this doesn't
var result2 = from p in Program
where (!x.HasValue)
select p;
result.Dump();
result2.Dump();
精彩评论