2012-07-04 41 views
2

我想要实现的是显示以/开始的行数(用户选择由comboBox1键入的)给定字符(由textbox1)。C#错误:使用“开关”时未分配的本地变量错误?

试图编译这段代码:

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'。我错过了什么?

+0

再次阅读错误消息。这是真的吗? – 2012-07-04 20:00:38

+0

[使用未分配的局部变量](http://stackoverflow.com/questions/4110251/use-of-unassigned-local-variable)可能的重复(这是“if”,但它与这里完全相同。-1是因为有太多太近的匹配。) – 2012-07-04 20:01:57

回答

4

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

int count = 0;

default条款添加到你的case语句:

default: count = 0;

switch声明不能保证进入这两种情况下,这样count可以保持未分配状态。如果需要的两种情况下,你应该在你的default情况下抛出异常:

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

你应该总是在你的switch语句使用default情况下,或者指定一个默认或防范意外状态。

+0

问题是,现在我得到的结果只有0.你认为有什么问题'count = File.ReadLines(openFileDialog1.FileName)。 Count(line => Regex.IsMatch(line,“^。*”+ needle +“。* $”)); '线? – heron

+0

@epic_syntax - 问题是你的'cboxSelection'变量不能保证匹配你有的任何一种情况,所以'count'不一定会在case块中被赋值。 – Lee

1
you can try with int count = 0; 

and add ; not , between two instructions 

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

是的,我试过了,问题是,现在我得到的结果只有0.你认为有什么问题count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line,“ ^。*“+ needle +”。* $“));行? – heron

+0

您也可以使用可为空的类型,尝试int?count = null; –

1

Count未分配给所有代码路径。如果您的交换机没有“开始”或“结束”,它将是null

您可以初始化:

int count = 0;

+0

是的,我做到了,问题是,现在我得到的结果只有0。您认为count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line,“^。*”+ needle +“。* $”)); line?有什么问题? – heron

1

那是因为你没有覆盖交换机中的所有可能性......所以在你的代码中,你得到label6.Text从未分配“路径” count

您应该初始值分配给count或添加default到交换机

+0

修正了问题是,现在我得到的结果只有0.你认为是否有任何问题计数= File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line,“^。*” +针+“。* $”));行? – heron

1

您的switch语句不包括所有的情况下(这现实不能,cboxSelection是一个字符串),所以这算一个可能性在使用之前没有分配任何东西。

将缺省情况添加到交换机以解决问题。

+0

已修复,问题是,现在我得到的结果只有0.你认为有什么问题count = File.ReadLines(openFileDialog1.FileName).Count (line => Regex.IsMatch(line,“^。*”+ needle +“。* $”)); line? – heron

+0

您是否尝试过检查您的正则表达式(例如http://chris.photobooks.com/regex /default.htm)? – Alan