我想要实现的是,显示以(用户通过 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/