문제

이 질문은 이미 여기에 답이 있습니다.

나는 이것을 몇 가지 다른 방법으로 시도해 왔지만, 그것이 할 수 없다는 결론에 도달하고 있습니다. 과거의 다른 언어에서 즐겼던 언어 기능입니다. 그냥 써야 할 것인가?

도움이 되었습니까?

해결책

아니요, 정적 인덱서는 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