简体   繁体   English

为什么C#中的这段代码不会引发错误

[英]Why doesn't this code in C# throw an error

Ideally the variable returnString being local variable and not initialised wouldn't have been able to be used and there would have been compile time error: 理想情况下,变量returnString是局部变量且未初始化,将无法使用,并且会出现编译时错误:

Use of unassigned local variable 'returnString' 使用未分配的局部变量“ returnString”

In fact, that's what I got in another context. 实际上,这就是我在另一种情况下得到的。 Still it works. 仍然有效。 Why? 为什么?

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace ConsoleApplication1
 {
     class a {
         public static string testMethod(){
             string returnString;
             try
             {
                 int a = 100;
                 int b = 0;
                 b = a / b;
                 returnString= Convert.ToString(a - b);
                 // return returnString;
             }
             catch (Exception ex)
             {
                  return  returnString = Convert.ToString(ex);
                  //throw ex;
             }
             return returnString;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // a A = new a();
            Console.WriteLine(a.testMethod());
            Console.ReadKey();
        }
    }
}

Decompiling the code (use release mode) often helps in such situations. 在这种情况下,反编译代码(使用发布模式)通常会有所帮助。 Here's the decompiled source generated by dotPeek: 这是dotPeek生成的反编译源:

public static string testMethod()
{
  try
  {
    int num1 = 100;
    int num2 = 0;
    int num3 = num1 / num2;
    return Convert.ToString(num1 - num3);
  }
  catch (Exception ex)
  {
    return Convert.ToString((object) ex);
  }
}

As you can see, for the compiler there's no uninitialized variable. 如您所见,对于编译器,没有未初始化的变量。 So why should it complain? 那么为什么要抱怨呢?

Because the compiler understands that it will be assigned later. 因为编译器知道它将在以后分配。

This does not compile, because it's possible that the variable is not assigned before returning it (if a == 2 for example): 这不会编译,因为有可能在返回变量之前未分配该变量(例如,如果a == 2):

    private string method(int a)
    {
        string result;

        if (a == 1)
        {
            result = "2334234";           
        }
        return result;
    }

Looks to me as if every path through the function returns an initialized variable. 在我看来,好像通过该函数的每个路径都返回一个初始化变量。 Either you successfully convert the division by zero, or as you will have an exception, you assign the variable the value of the exception. 您成功地将除数转换为零,或者因为您将遇到异常,所以给变量分配了异常的值。 You are always going to have a properly assigned value and the compiler sees that. 您将始终拥有一个正确分配的值,编译器会看到该值。

Your code either sets returnString if: 您的代码可以在以下情况下设置returnString

  1. Code doesn't throw an exception before setting the returnString variable inside the try/catch block. try/catch块中设置returnString变量之前,代码不会引发异常。

  2. If the code in the try block throws an exception, returnString will be assigned. 如果try块中的代码引发异常,则将分配returnString

Conclusion: there's no case where the returnString variable could be unassigned. 结论:在任何情况下都不会取消分配returnString变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM