简体   繁体   English

C#错误:使用“switch”时未分配的局部变量错误?

[英]C# Error: Unassigned local variable error when using “switch”?

What I want to achieve is, to show count of lines ending with/starting with (user selects type by comboBox1) given character (by textbox1). 我想要实现的是,显示以/开头的行数(用户通过comboBox1选择类型)给定字符(通过textbox1)。

Trying to compile this code: 试图编译这段代码:

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.";

Getting error message: Use of unassigned local variable 'count' . 获取错误消息: Use of unassigned local variable 'count' What am I missing? 我错过了什么?

Your local count variable has not been definitely assigned at the point of use. 您的本地count变量尚未在使用点明确分配。 Either declare it as 要么声明为

int count = 0 ; int count = 0 ;

or add a default clause to your case statement: 或者在case语句中添加一个default子句:

default: count = 0;

Your switch statement is not guaranteed to enter either case, so count can remain unassigned. 您的switch语句无法保证输入任何一种情况,因此count可以保持未分配状态。 If one of the two cases is required, you should throw an exception in your default case: 如果需要这两种情况之一,则应在default情况下抛出异常:

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

You should always use a default case in your switch statements either to assign a default or to guard against unexpected states. 您应始终在switch语句中使用default大小写来指定默认值或防止意外状态。

you can try with int count = 0;

and add ; not , between two instructions

string needle=textBox1.Text.Trim(); 
cboxSelection = comboBox1.Text;

Count isn't assigned on all code paths. 未在所有代码路径上分配Count If your switch doesn't have "Starting with" or "Ending with", it will be null . 如果您的开关没有“开始于”或“结束于”,则它将为null

You can initialize it: 你可以初始化它:

int count = 0;

It's because you are not covering all possibilities within your switch... so there is a "path" in your code in which you get to label6.Text never assigning count . 这是因为你没有覆盖你的交换机中的所有可能性...所以你的代码中有一个“路径”,你可以在其中获得label6.Text永远不会分配count

You should either assign an initial value to count or add a default to your switch 您应该为count分配初始值或为交换机添加default

Your switch statement does not cover all cases (it realistically cannot, cboxSelection being a string), so there is a possibility that count does not get anything assigned to before you use it. 你的switch语句并不涵盖所有情况(实际上它不能,cboxSelection是一个字符串),所以在你使用它之前,count可能没有分配任何东西。

Add a default case to the switch to fix it. 将一个默认大小写添加到交换机以修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM