编译器错误 CS0165

使用了未赋值的局部变量“name”

C# 编译器不允许使用取消初始化的变量。 如果编译器检测到所使用的某个变量可能尚未初始化,就会生成 编译错误 CS0165。 有关详细信息,请参阅字段。 如果编译器遇到可能会导致使用未赋值变量的构造,即使特定代码不使用该变量,也会生成此错误。 这样可以避免对明确赋值使用过度复杂的规则。

有关详细信息,请参阅递归 lambda 为何一定会导致赋值错误?

示例 1

下面的示例生成 CS0165:

// CS0165.cs  
using System;  
  
class MyClass  
{  
    public int i;  
}  
  
class MyClass2  
{  
    public static void Main(string[] args)  
    {  
        // i and j are not initialized.  
        int i, j;  
  
        // You can provide a value for args[0] in the 'Command line arguments'  
        // text box on the Debug tab of the project Properties window.  
        if (args[0] == "test")  
        {  
            i = 0;  
        }  
        // If the following else clause is absent, i might not be  
        // initialized.  
        //else  
        //{  
        //    i = 1;  
        //}  
  
        // Because i might not have been initialized, the following
        // line causes CS0165.  
        j = i;  
  
        // To resolve the error, uncomment the else clause of the previous  
        // if statement, or initialize i when you declare it.  
  
        // The following example causes CS0165 because myInstance is  
        // declared but not instantiated.  
        MyClass myInstance;  
        // The following line causes the error.  
        myInstance.i = 0;
  
        // To resolve the error, replace the previous declaration with  
        // the following line.  
        //MyClass myInstance = new MyClass();  
    }  
}  

示例 2

编译器错误 CS0165 可能发生在递归委托定义中。 若要避免此错误,可在两个语句中定义委托,以使变量在初始化之前不会被投入使用。 下面的示例演示此错误和解决方案。

class Program  
{  
    delegate void Del();  
    static void Main(string[] args)  
    {  
        // The following line causes CS0165 because variable d is used
        // as an argument before it has been initialized.  
        Del d = delegate() { System.Console.WriteLine(d); };
  
        //// To resolve the error, initialize d in a separate statement.  
        //Del d = null;  
        //// After d is initialized, you can use it as an argument.  
        //d = delegate() { System.Console.WriteLine(d); };  
        //d();  
    }  
}  

Load(String)