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

30

在.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

3个回答

43
根据这个网站,可以使用属性来重命名索引器。
public class MyClass
{
    public object Item { get; set; }
    [System.Runtime.CompilerServices.IndexerName("MyItem")]
    public object this[string index] { get { return null; } set { } }
}

27

C#内部为不支持索引器的语言创建了一个名为Item的属性。 您可以使用IndexerNameAttribute来控制此名称,就像这样:

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

4
如果我没记错的话,这样的索引器可以通过VB.Net中的"Item()"方法访问。这就是"defined twice"的来源所在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接