هل المفهرسات الثابتة غير مدعومة في C#؟[ينسخ]

StackOverflow https://stackoverflow.com/questions/154489

  •  03-07-2019
  •  | 
  •  

سؤال

هذا السؤال لديه بالفعل إجابة هنا:

لقد حاولت ذلك بعدة طرق مختلفة، لكنني توصلت إلى نتيجة مفادها أنه لا يمكن القيام بذلك.إنها ميزة لغوية استمتعت بها من اللغات الأخرى في الماضي.هل هو مجرد شيء يجب أن أشطبه؟

هل كانت مفيدة؟

المحلول

لا، المفهرسات الثابتة غير مدعومة في C#.ومع ذلك، على عكس الإجابات الأخرى، أرى أنه يمكن بسهولة أن يكون هناك فائدة من الحصول عليها.يعتبر:

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

أعتقد أنه نادرًا ما يتم استخدامه، ولكن أعتقد أنه من الغريب أنه محظور - فهو يعطي عدم التماثل دون سبب محدد بقدر ما أستطيع رؤيته.

نصائح أخرى

يمكنك محاكاة المفهرسات الثابتة باستخدام الخصائص المفهرسة الثابتة:

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")   

لا، ولكن من الممكن إنشاء حقل ثابت يحتوي على مثيل لفئة تستخدم مفهرسًا...

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top