编译器错误 CS0106

修饰符“modifier”对该项无效

类或接口的成员标记有无效的访问修饰符。 下面的示例介绍其中某些无效的修饰符:

  • 本地函数中不允许使用静态修饰符。 从 C# 8.0 开始支持静态本地函数功能。 尝试使用此功能时,不支持 C# 8.0 的编译器会生成 CS0106。 但是,支持 C# 8.0 但将语言版本设置为 C# 8.0 及更低版本的编译器将生成一个诊断,该诊断建议使用 C# 8.0 或更高版本。

  • 显式接口声明上不允许使用 public 关键字。 在这种情况下,从显式接口声明删除 public 关键字。

  • 显式接口声明上不允许具有抽象关键字,因为永远不能重写显式接口实现。

  • 本地函数中不允许出现访问修饰符。 本地函数始终为私有函数。

  • 类类型中的方法不允许使用 readonly 关键字,ref readonly 返回除外(readonly 关键字必须出现在 ref 关键字之后)。

在 Visual Studio 的先前版本中,类上不允许具有 static 修饰符,但允许具有以 Visual Studio 2005 开头的 static 类。

有关详细信息,请参阅接口

示例

下面的示例生成 CS0106:

// CS0106.cs
namespace MyNamespace
{
   interface I
   {
      void M1();
      void M2();
   }

   public class MyClass : I
   {
      public readonly int Prop1 { get; set; }   // CS0106
      public int Prop2 { get; readonly set; }   // CS0106

      public void I.M1() {}   // CS0106
      abstract void I.M2() {}   // CS0106

      public void AccessModifierOnLocalFunction()
      {
         public void LocalFunction() {}   // CS0106
      }

      public readonly void ReadonlyMethod() {}   // CS0106
      // Move the `readonly` keyword after the `ref` keyword
      public readonly ref int ReadonlyBeforeRef(ref int reference)   // CS0106
      {
         return ref reference;
      }

      public static void Main() {}
   }

   public readonly class ReadonlyClass {}   // CS0106
}