C#编译器认为应该初始化这些变量

FMM*_*FMM 1 c#

以下是我正在编写的应用程序示例:

        bool x3k = false, y3k = false;

        // all of these functions return nullable ints (int?)
        var comparison = 
            DoSomething(x, y)
            ?? DoSomething2(x, y)
            ?? DoSomething3(x, y, out x3k, out y3k)
            ?? DoSomething4(x, y)
            ?? DoSomething5(x, y);

        if (comparison.HasValue)
            return comparison.Value;

        if (x3k) // compiler error here if I don't init x3k
        {

        }
Run Code Online (Sandbox Code Playgroud)

我不明白,在零合并链中,如果comparison是x3k可以未初始化null,我不会提前返回.这里发生了什么?

Cor*_*son 5

您遇到短路行为:如果DoSomethingDoSomething2返回非空的东西,DoSomething3将永远不会执行,从而离开x3ky3k未初始化.

  • @FMM编译器并不那么聪明. (5认同)