2011-06-03 19 views
-1

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

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

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

     return -1; 
    } 
    } 
} 
+0

在4.0 。 – 2011-06-03 18:11:05

+1

“'Fred.this [string]':无法在静态类中声明索引器”和“修饰符'static'对此项无效”。 – sisve 2011-06-03 18:11:52

回答

1

这不会编译。在编译过程中,Visual Studio的报告(2个)错误,CS0106CS0720

C:\路径\为\的Program.cs(5,23):错误CS0106:修饰语 '静态' 是无效的这个项目 C:\ Path \ To \ Program \ Program.cs(5,23):错误CS0720:'Fred.this [string]':无法在静态类中声明索引器

+0

我知道了! SORRYY! – 2011-06-03 18:11:41

+0

@Tom:没关系 - 有时会发生;) – 2011-06-03 18:11:57