Unexpected CS0165 Use of unassigned local variable for probably assigned field

问题描述 投票:0回答:0

为什么这段 C# 代码似乎不正确导致编译器错误

CS0165 使用未分配的局部变量

即使字段分配给非空值取决于两个 if 块中完全相同的、可能不变的条件:


private void Method()
    bool flag = true; // make this const to fold the branching the code and the compiler error goes away
    string field;

    if (flag) // or remove this ofc
        field = "A"; // field is obviously assigned here

    // other code necessary before the following block

    // originally contained in another if-block...
    if (flag)
        field += "B"; // compiles with [CS0165]

    // ... remaining code omitted




c# .net-6.0 rider
© www.soinside.com 2019 - 2024. All rights reserved.