![](/img/trans.png)
[英]“Use of unassigned local variable” compiler error for switch statement in C#?
[英]C# Error: Unassigned local variable error when using “switch”?
我想要实现的是,显示以/开头的行数(用户通过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.";
获取错误消息: Use of unassigned local variable 'count'
。 我错过了什么?
您的本地count
变量尚未在使用点明确分配。 要么声明为
int count = 0
;
或者在case语句中添加一个default
子句:
default: count = 0;
您的switch
语句无法保证输入任何一种情况,因此count
可以保持未分配状态。 如果需要这两种情况之一,则应在default
情况下抛出异常:
default: throw new ArgumentException("Invalid selection");
您应始终在switch语句中使用default
大小写来指定默认值或防止意外状态。
you can try with int count = 0;
and add ; not , between two instructions
string needle=textBox1.Text.Trim();
cboxSelection = comboBox1.Text;
未在所有代码路径上分配Count
。 如果您的开关没有“开始于”或“结束于”,则它将为null
。
你可以初始化它:
int count = 0;
这是因为你没有覆盖你的交换机中的所有可能性...所以你的代码中有一个“路径”,你可以在其中获得label6.Text
永远不会分配count
。
您应该为count
分配初始值或为交换机添加default
你的switch语句并不涵盖所有情况(实际上它不能,cboxSelection是一个字符串),所以在你使用它之前,count可能没有分配任何东西。
将一个默认大小写添加到交换机以修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.