c# code seems to get optimized in an invalid way such that an object value becomes null

后端 未结 3 771
萌比男神i
萌比男神i 2021-02-05 13:13

I have the following code that exhibits a strange problem:

var all = new FeatureService().FindAll();
System.Diagnostics.Debug.Assert(all != null, \"FindAll must          


        
3条回答
  •  孤街浪徒
    2021-02-05 13:43

    Left for posterity, this is not the problem.

    See my new answer.


    Here's what I believe.

    Contrary to what you're saying, I believe the program is not in fact crashing in any of the lines posted, but instead crashes on one of the lines following them, which you haven't posted.

    The reason I believe this is that I also believe you're doing a Release-build, in which case both Debug lines will be removed, since they're tagged with a [Conditional("DEBUG")] attribute.

    The clue here is that the all variable has been optimized away, and this should only happen during a Release-build, not a Debug-build.

    In other words, I believe the all variable is actuall null after all, and the Debug lines aren't executed, because they're not compiled into the assembly. The debugger is dutifully reporting that the all variable no longer exists.

    Note that all of this should be easy to test. Just place a breakpoint on the first of the two Debug-lines that you've posted. If the breakpoint is hit, my hypothesis is most likely wrong. If it doesn't (and I'm going to guess that the breakpoint symbol shows up as a hollow circle at runtime), then those lines aren't compiled into the assembly.

提交回复
热议问题