这是我经常遇到的一个错误。虽然我设法用某种方式绕过了它,但它真的让我很烦。 在下面的代码片段中,我想防止来自 myRequest.GetResponse() 的异常
WebRequest myRequest = WebRequest.Create(baseUri.OriginalString);
WebResponse myResponse;
Stream myStream;
StreamReader reader;
try
{
myResponse = myRequest.GetResponse();
myStream = myResponse.GetResponseStream();
reader = new StreamReader(myStream);
}
catch (WebException status)
{
txtConsole.AppendText("Error in GetLinks::WebException\n" + status.Response);
txtConsole.AppendText(Environment.NewLine);
}
catch
{
txtConsole.AppendText("Some error in GetLinks");
txtConsole.AppendText(Environment.NewLine);
}
Regex regex = new Regex(@"\s*(?i)href\s*=\s*(\""([^""]*\"")|'[^']*'|([^'"">\s]+))", RegexOptions.IgnoreCase);
MatchCollection splits = regex.Matches(reader.ReadToEnd());
现在,当我尝试构建/编译代码时,它说
"Use of unassigned local variable 'reader'"
现在我的问题是,如果 try 语句运行顺利且没有抛出任何异常,为什么编译器不能访问 try block 内分配给 reader 的值?
最佳答案
您正在使用一个变量,该变量在 try/catch block 中分配,但位于该 block 之外。您需要将整个代码移动到 try block 中。
您可以像@Svexo 建议的那样将 null
分配给它,但是如果流出错,这将引发异常。
关于c# - 如何避免在 try-catch block 内定义 'Unassigned Local Variable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16999410/