通常编译器禁止使用任何未分配的局部变量,但在以下情况下则不然。为什么?
private void Main()
{
// This local variable is unassigned.
string myVar;
try
{
// The Throw() method prevents the assignment from happening...
myVar = Throw();
}
finally
{
// ... so myVar is still unassigned.
}
// Here we use myVar, which is unassigned, and the compiler is not complaining.
if (myVar.Equals("Something"))
{
// ...
}
}
private string Throw()
{
throw new Exception();
}
最佳答案
示例中的异常未被 Main()
捕获。因此,如果抛出异常,则finally
block 之后的代码是不可访问的,如果未抛出异常,则发生赋值。这就是为什么在任何情况下都不能使用未分配的变量。由于它不可能发生,编译器不会报告它。
关于c# - 为什么这里允许使用未分配的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70372283/