帮助解决简单的C#错误

Rya*_*yer 2 .net c#

我正在编写这个小程序,从文本文件中提取任意数量的电子邮件地址.我收到两个错误,"使用未分配的局部变量." 而且我不确定为什么.

static void Main(string[] args)
{
string InputPath = @"C:\Temp\excel.txt";
string OutputPath = @"C:\Temp\emails.txt";
string EmailRegex = @"^(?:[a-zA-Z0-9_'^&/+-])+(?:\.(?:[a-zA-Z0-9_'^&/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$";
string Text = String.Empty;
StringBuilder Output;
List<string> Emails;

using (TextReader tr = new StreamReader(InputPath))
{
    Text = tr.ReadToEnd();
}

MatchCollection Matches = Regex.Matches(Text,EmailRegex);

foreach (Match m in Matches)
{
    Emails.Add(m.ToString().Trim()); // one error is here
}

foreach (String s in Emails)
{
    Output.Append(s + ","); // the other error is here
}

using (TextWriter tw = new StreamWriter(OutputPath))
{
    tw.Write(Output.ToString());
}
} 
Run Code Online (Sandbox Code Playgroud)

对不起格式化...我有点紧迫!

编辑:哇.我是个白痴 - 一定是因为我时间紧迫!!!!

Dav*_*kle 21

您没有初始化StringBuilder和List.

StringBuilder Output = new StringBuilder();
List<string> Emails = new List<String>();
Run Code Online (Sandbox Code Playgroud)


lav*_*nio 9

问题出在这里:

StringBuilder Output;
List<string> Emails;
Run Code Online (Sandbox Code Playgroud)

你还没有初始化EmailsOutput.尝试:

StringBuilder Output = new StringBuilder();
List<string> Emails = new List<string>();
Run Code Online (Sandbox Code Playgroud)


Mit*_*eat 8

您没有创建Stringbuilder或电子邮件列表:

StringBuilder Output = new StringBuilder();
List<string> Emails = new List<string>(); 
Run Code Online (Sandbox Code Playgroud)


d4n*_*4nt 8

您的"输出"和"列表"变量未分配对象实例.更改:

StringBuilder Output;
List<string> Emails;
Run Code Online (Sandbox Code Playgroud)

StringBuilder Output = new StringBuilder();
List<string> Emails = new List<string>();
Run Code Online (Sandbox Code Playgroud)