【问题标题】:Class with indexer and property named "Item"具有索引器和名为“Item”的属性的类
【发布时间】:2011-07-03 21:11:03
【问题描述】:

是否可以在 .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

【问题讨论】:

    标签: c# .net indexer


    【解决方案1】:

    基于this site,可以使用属性重命名Indexer

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2023-03-05
          • 1970-01-01
          • 1970-01-01
          • 2015-10-12
          • 2020-01-01
          • 1970-01-01
          • 2019-02-23
          • 2021-02-06
          • 1970-01-01
          相关资源
          最近更新 更多