为什么这段 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
,那么编译器应该折叠代码并且错误消失,但这不是我正在使用的代码中的一个选项。
• How to return multiple results in Postgres but I need to use a variable
• How to fix The local variable line may not have been initailized error
• Route Admin/AdminController 未找到新的 Laravel 项目 [重复]
• dspace 7 angular app 添加第三方 NPM 模块
• FastAPI 本地服务器:每个请求都使用不同的端口 -> port in use error
• 如何显示限制人数为255的人数?类似于 Twitter,并且不使用最大长度?
• Javascript Uncaught SyntaxError: Invalid or unexpected token
• 为什么 (variable++) 与 Java 中的 (variable=variable+1) 不同?
• 为什么我的代码 returnin error unexpected symbol near for?
• 护照认证问题