【问题标题】:Are static indexers not supported in C#? [duplicate]C# 不支持静态索引器吗? [复制]
【发布时间】:2010-09-14 08:18:22
【问题描述】:

我已经尝试了几种不同的方法,但我得出的结论是无法做到。这是我过去从其他语言中喜欢的语言功能。这只是我应该注销的东西吗?

【问题讨论】:

    标签: c# .net clr


    【解决方案1】:

    不,C# 不支持静态索引器。然而,与其他答案不同,我看到拥有它们很容易。考虑:

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

    我怀疑它相对很少使用,但我认为它被禁止很奇怪 - 据我所知,它没有特别的原因造成不对称。

    【讨论】:

    • 没错。他们有他们的位置。在这里谈论设计问题的其他人显然从未使用过允许的经典语言,因为它们非常有帮助。
    • 是的。我的观点正是。它们在建筑中占有非常重要的地位。我猜有些人蒙上了眼罩!
    • 废话。现在我要写一个静态方法 Cache.Get(key) 而不是 Cache[key]...
    • 作为一个社区,我们何时才能意识到人们如何使用某些工具是不可能的。我喜欢 C# 中的这个功能。
    • 每次您需要此答案时+1!
    【解决方案2】:

    您可以使用静态索引属性模拟静态索引器:

    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()); }
        }
    }
    

    用法:

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

    【讨论】:

    • 虽然 Jon 的回答(像往常一样)是最正确的,但在某些情况下这并不是一个糟糕的选择。
    【解决方案3】:

    不,但可以创建一个静态字段来保存使用索引器的类的实例...

    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; }
             }
          }
       }
    }
    

    ...可以按照您想要的方式访问。这可以在即时窗口中测试...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2011-04-03
      • 1970-01-01
      • 2010-09-28
      相关资源
      最近更新 更多