【问题标题】:How to define Indexer behaviour to an Interface?如何定义接口的索引器行为?
【发布时间】:2012-03-24 02:29:55
【问题描述】:

是否可以从界面添加索引器行为?

类似这样的:

interface IIndexable<T>
{
   T this[string index];
}

【问题讨论】:

    标签: c# interface


    【解决方案1】:

    一个更通用的接口(取自IDictionary&lt;,&gt;)是:

    interface IIndexable<TKey, TValue>
    {
        TValue this[TKey key] { get; set; }
    }
    

    我只是想知道为什么他们没有将它包含在 mscorlib 中,以便 IDictionary 可以实现它。这是有道理的。

    【讨论】:

      【解决方案2】:

      是的,这是可能的。事实上,您所缺少的只是索引器上的 getter/setter。只需添加如下:

      interface IIndexable<T>
      {
           T this[string index] {get; set;}
      }
      

      【讨论】:

        【解决方案3】:

        来自MSDN

        public interface ISomeInterface
        {
            //...
        
            // Indexer declaration:
            string this[int index]
            {
                get;
                set;
            }
        }
        

        可以在接口上声明索引器(C# 参考)。的访问者 接口索引器与类索引器的访问器不同 以下方式:

        • 接口访问器不使用修饰符。
        • 接口访问器没有主体。

        【讨论】:

          猜你喜欢
          • 2012-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-17
          • 1970-01-01
          相关资源
          最近更新 更多