編譯器錯誤 CS0151

更新:2007 年 11 月

錯誤訊息

必須是整數類資料型別的值

在需要整數類資料型別的情況下使用變數。如需詳細資訊,請參閱資料型別 (C# 程式設計手冊)

範例

這種錯誤會發生在沒有轉換或是可用的隱含轉換產生模稜兩可的情況時。下列範例會產生 CS0151。

// CS0151.cs
public class MyClass
{
   public static implicit operator int (MyClass aa)
   {
      return 0;
   }

   public static implicit operator long (MyClass aa)
   {
      return 0;
   }

   public static void Main()
   {
      MyClass a = new MyClass();

      // Compiler cannot choose between int and long
      switch (a)   // CS0151
      // try the following line instead
      // switch ((int)a)
      {
         case 1:
            break;
      }
   }
}

在 Visual Studio 2008 以後的版本中,void 的方法引動會產生 CS0151。您可以呼叫傳回整數類資料型別 (Integral Type) (如 intlong) 的方法,以修正這個錯誤。

class C
{
    static void Main()
    {

        switch (M()) // CS0151
        {
            default:
                break;
        }
    }

    static void M()
    {
    }
}