下面的方法编译很好.
string DoSomething(int x) {
string s;
if(x < 0)
s = "-";
else if(x > 0)
s = "+";
else
return "0";
return DoAnotherThing(s);
}
Run Code Online (Sandbox Code Playgroud)
但是当我在foreach循环中编写相同的代码并使用yield return而不是return我得到Use of unassigned local variable 's'编译错误.
// Causes compile error
IEnumerable<string> DoSomethingWithList(IEnumerable<int> xList) {
foreach(var x in xList) {
string s;
if(x < 0)
s = "-";
else if(x > 0)
s = "+";
else
yield return "0";
// COMPILE ERROR: Use of unassigned local variable 's'
yield return DoAnotherThing(s);
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说,s当代码到达那一行时,它是如此明显.可能是这个错误的原因,可能是编译器错误?
这不是编译器错误.(其中很少有,真的,所以击中它的机会很小.)这是你的代码中一个非常简单的错误.
当值为x零时,您的代码进入else块并产生"0".当请求下一个值时,该方法继续并执行以下行:
yield return DoAnotherThing(s);
Run Code Online (Sandbox Code Playgroud)
...此时您尚未指定任何值s.