C# 错误 : Unassigned local variable error when using "switch"?

标签 c# visual-studio compiler-errors

我想要实现的是,显示以(用户通过 comboBox1 选择类型)给定字符(通过 textbox1)结束/开始的行数。

尝试编译这段代码:

string needle=textBox1.Text.Trim(), cboxSelection = comboBox1.Text;
int count;
switch (cboxSelection)
{
    case "Starting with":
        count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line, "^" + needle + ".*$"));
        break;
    case "Ending with":
        count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line, "^.*" + needle + ".*$"));                    
        break;
}
string strCount = count.ToString(); // error line
label6.Text = "There are " + strCount + " lines " + cboxSelection + " " + needle + " character.";

获取错误消息:使用未分配的局部变量“count”。我错过了什么?

最佳答案

您的本地 count 变量在使用时尚未明确分配。要么将其声明为

int 计数 = 0;

或者在你的 case 语句中添加一个 default 子句:

默认: 计数 = 0;

您的 switch 语句不能保证进入任何一种情况,因此 count 可以保持未分配状态。如果需要这两种情况之一,您应该在 default 情况下抛出异常:

default: throw new ArgumentException("Invalid selection");

您应该始终在 switch 语句中使用 default case 来分配默认值或防止意外状态。

关于C# 错误 : Unassigned local variable error when using "switch"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334764/

相关文章:

c# - Monotouch 中的 CGAffineTransformScale

c# - 使用 linq 删除列表中的重复项

java - 为什么 Set 被编译器标记为 "not a known variable in this context"?

c# - 无法将 "obj\Debug\Program.exe"复制到 "bin\Debug\Program.exe"。超过重试次数 10。失败

macos - "ResolvePackageAssets"任务意外失败

c# - 如何修复2019版中的Unity编译器错误?

c# - 调度任务c#

c# - GAE Flexible 不使用 CORS 返回正确的响应 header

visual-studio-2010 - 安装 Resharper 后如何在 Visual Studio 中恢复导航到对话框

javascript - 尝试引用index.js 文件时,Visual Studio 无法识别 src 属性