具有索引器和名为“Item”的属性的类

是否可以在.NET 4中创建一个类:

  1. 一个索引器,
  2. 一个名为“Item”的属性?

例如,这个C#类不会为我编译:

public class MyClass { public object Item { get; set; } public object this[string index] { get { return null; } set { } } } 

编译器给出错误CS0102 :

“MyClass”类型已包含“Item”的定义

虽然我只是明确定义Item一次。

基于此站点 ,可以使用属性重命名索引器

 public class MyClass { public object Item { get; set; } [System.Runtime.CompilerServices.IndexerName("MyItem")] public object this[string index] { get { return null; } set { } } } 

C#内部为不支持索引器的语言创建一个名为Item的属性。 您可以使用IndexerNameAttribute控制此名称,如下所示:

 [IndexerName("MyIndexer")] public object this[string index] { get { return blah; } } 

如果我没记错的话,可以通过“Item()”方法从VB.Net访问这样的索引器。 那将是“定义两次”的地方。