Are static indexers not supported in C#? [duplicate]

北城余情 提交于 2019-11-26 14:33:34

问题


This question already has an answer here:

  • Static Indexers? 7 answers

I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?


回答1:


No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:

Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")

It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.




回答2:


You can simulate static indexers using static indexed properties:

public class MyEncoding
{
    public sealed class EncodingIndexer
    {
        public Encoding this[string name]
        {
            get { return Encoding.GetEncoding(name); }
        }

        public Encoding this[int codepage]
        {
            get { return Encoding.GetEncoding(codepage); }
        }
    }

    private static EncodingIndexer StaticIndexer;

    public static EncodingIndexer Items
    {
        get { return StaticIndexer ?? (StaticIndexer = new EncodingIndexer()); }
    }
}

Usage:

Encoding x = MyEncoding.Items[28591]; // Equivalent to Encoding.GetEncoding(28591)   
Encoding y = MyEncoding.Items["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")   



回答3:


No, but it is possible to create a static field that holds an instance of a class that uses an indexer...

namespace MyExample {

   public class Memory {
      public static readonly MemoryRegister Register = new MemoryRegister();

      public class MemoryRegister {
         private int[] _values = new int[100];

         public int this[int index] {
            get { return _values[index]; }
            set { _values[index] = value; }
         }
      }
   }
}

...Which could be accessed in the way you are intending. This can be tested in the Immediate Window...

Memory.Register[0] = 12 * 12;
?Memory.Register[0]
144


来源:https://stackoverflow.com/questions/154489/are-static-indexers-not-supported-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!