IT

C #에서 [] 연산자를 오버로드하는 방법

lottoking 2020. 3. 22. 10:51

C #에서 [] 연산자를 오버로드하는 방법 [중복]


이 질문에는 이미 답변이 있습니다.

클래스에 연산자를 추가하고 싶습니다. 현재 연산자 GetValue()로 바꾸려 방법이 []있습니다.

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index) => values[index];
}

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}

나는 이것이 당신이 찾고있는 것이라고 믿습니다.

인덱서 (C # 프로그래밍 가이드)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get => arr[i];
        set => arr[i] = value;
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

[] 연산자를 인덱서라고합니다. 정수, 문자열 또는 키로 사용하려는 다른 유형을 취하는 인덱서를 제공 할 수 있습니다. 구문은 속성 접근 자와 동일한 원칙에 따라 간단합니다.

예를 들어, a int가 키 또는 인덱스 인 경우 :

public int this[int index]
{
    get => GetValue(index);
}

인덱서가 읽기 전용이 아니라 읽기 및 쓰기가되도록 set 접근자를 추가 할 수도 있습니다.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

다른 유형을 사용하여 인덱싱하려면 인덱서의 서명 만 변경하면됩니다.

public int this[string index]
...

public int this[int index]
{
    get => values[index];
}

참고 URL : https://stackoverflow.com/questions/424669/how-do-i-overload-the-operator-in-c-sharp