C#静态索引器不应编译,但会编译

C#静态索引器不应编译,但会编译,c#,static,indexer,C#,Static,Indexer,我意识到C#中不能有静态索引器。但是为什么下面的代码能够正确编译(在C#4.0下) 因为Fred是一个静态类,所以它甚至不能被实例化。声明的静态索引器没有意义,但编译器允许它。为什么?我无法想象这是一个编译器错误这么晚才进入语言 public static class Fred { public static int this[String str] { get { if (str != null) return str.Length; re

我意识到C#中不能有静态索引器。但是为什么下面的代码能够正确编译(在C#4.0下)

因为Fred是一个静态类,所以它甚至不能被实例化。声明的静态索引器没有意义,但编译器允许它。为什么?我无法想象这是一个编译器错误这么晚才进入语言

public static class Fred {
  public static int this[String str] {
    get {
      if (str != null)
        return str.Length;

      return -1;
    }
  }
}

这是不可编译的。在编译过程中,Visual Studio报告2个错误,以及:

C:\Path\To\Program.cs(5,23):错误CS0106:修饰符“static”对此项无效
C:\Path\To\Program\Program.cs(5,23):错误CS0720:“Fred.this[string]”:无法在静态类中声明索引器


没有在4.0中为我编译。“'Fred.this[string]':无法在静态类中声明索引器”和“修饰符'static'对此项无效”。@Tom:没关系-有时会发生;)