编译器错误 CS0165

更新: 2008 年 7 月

错误消息

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

C# 编译器不允许使用未初始化的变量。如果编译器检测到使用了可能未初始化的变量,就会生成 CS0165。有关更多信息,请参见字段(C# 编程指南)。请注意,当编译器遇到可能会导致使用未赋值变量的构造时,即使您的特定代码不会使用该变量,也会生成此错误。这样可以避免对明确赋值使用过度复杂的规则。

如果遇到此错误

有关更多信息,请参见 https://blogs.msdn.com/ericlippert/archive/2006/08/18/706398.aspx

示例

下面的示例生成 CS0165:

// CS0165.cs
using System;

class MyClass
{
   public int i;
}

class MyClass2
{
   public static void Main(string [] args)
   {
      int i, j;
      if (args[0] == "test")
      {
         i = 0;
      }

      /*
      // to resolve, either initialize the variables when declared
      // or provide for logic to initialize them, as follows:
      else
      {
         i = 1;
      }
      */

      j = i;   // CS0165, i might be uninitialized

      MyClass myClass;
      myClass.i = 0;   // CS0165
      // use new as follows
      // MyClass myClass = new MyClass();
      // myClass.i = 0;
   }
}

下面的代码在 Visual Studio 2008 中而不是在 Visual Studio 2005 中生成 CS0165:

//cs0165_2.cs
class Program
{
    public static int Main()
    {
        int i1, i2, i3, i4, i5;

        // this is an error, because 'as' is an operator
       // that is not permitted in a constant expression.
        if (null as object == null)
            i1 = 1;

        // this is an error, because 'is' is an operator that
        //  is not permitted in a constant expression.
        // warning CS0184: The given expression is never of the provided ('object') type
        if (!(null is object))
            i2 = 1;

        // this is an error, because a variable j3 is not
        // permitted in a constant expression.
        int j3 = 0;
        if ((0 == j3 * 0) && (0 == 0 * j3))
            i3 = 1;

        // this is an error, because a variable j4 is not
        // permitted in a constant expression.
        int j4 = 0;
        if ((0 == (j4 & 0)) && (0 == (0 & j4)))
            i4 = 1;

        // this might be an error, because a variable j5 is not
        // permitted in a constant expression.
        // warning CS1718: Comparison made to same variable; did you mean to compare something else?
        int? j5 = 1;
        if (j5 == j5)
            i5 = 1;


        System.Console.WriteLine("{0}{1}{2}{3}{4}{5}", i1, i2, i3, i4, i5); //CS0165

        return 1;
    }

}

此错误发生在递归委托定义中,通过在以下两个语句中定义该委托可避免此错误:

class Program
    {
        delegate void Del();
        static void Main(string[] args)
        {
            Del d = delegate() { System.Console.WriteLine(d); }; //CS0165
// Try this instead:
// Del d = null;
//d = delegate() { System.Console.WriteLine(d); };
            d();
        }
    }

修订记录

日期

历史记录

原因

2008 年 7 月

添加了有关递归委托的文本和代码示例。

内容 Bug 修复