为什么这段 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
}
这是对更复杂的代码的简化,依赖于标志和条件编译以提高执行效率,并且没有块不能折叠在一起。本地标志最初是一个属性,其值可能无法在上下文中保持不变。
有趣的是,如果标志被标记为
const
,那么编译器应该折叠代码并且错误消失,但这不是我正在使用的代码中的一个选项。