共用方式為


編譯器錯誤 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 中產生 CS0165,但不會在 Visual Studio 2005 中產生該錯誤:

//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 修正。