c# - 为什么这里允许使用未分配的局部变量?

标签 c# .net

通常编译器禁止使用任何未分配的局部变量,但在以下情况下则不然。为什么?

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/

相关文章:

c# - 如何修复 "No overload for method ' ' takes 0 arguments"?

c# - 为什么 Array 类不直接公开其索引器?

c# - PRISM (Unity) 中的 ViewModelLocator 在模块中不起作用

c# - 锁变量应该声明为 volatile 吗?

c# - 可空字符串 (string?) 和初始化为可原谅空值的字符串 (字符串 s = null!) 之间有什么区别

c# - HttpClient GetAsync 线程池饥饿

c# - 显示希伯来语 sqlplus

.net - SHA256Managed 在 x64 构建中的速度是原来的两倍——这是典型的吗?

C#:如何将任意字符串解析为表达式树?

c# - 我可以停止 IIS 吗?