문제

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

수업에 연산자를 추가하고 싶습니다. 나는 현재 a GetValue() 교체하고 싶은 방법 [] 운영자.

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

    public int GetValue(int index)
    {
        return values[index];
    } 
}
도움이 되었습니까?

해결책

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

다른 팁

나는 이것이 당신이 찾고있는 것이라고 생각합니다.

인덱서 (C# 프로그래밍 안내서)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return 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]);
    }
}

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

예를 들어, 귀하의 경우 an int 키 또는 색인입니다.

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

또한 세트 액세서를 추가하여 인덱서가 읽기 전용이 아니라 읽기 및 쓰기가되도록 할 수도 있습니다.

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

  set
  {
    SetValue(index, value);
  }
}

다른 유형을 사용하여 색인을 원한다면 인덱서의 서명 만 변경합니다.

public int this[string index]
...
public int this[int index]
{
    get
    {
        return values[index];
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top