2016-07-07 1 views
-2

일이야 다음 this은 무엇누군가이 C# 구문을 설명 할 수 있습니까? 실제로 무슨

public decimal[] Coefficients; 
public decimal this[int i] 
{ 
    get { return Coefficients[i]; } 
    set { Coefficients[i] = value; } 
} 

역할을 하는가? decimal의 확장 기능입니까?

+5

클래스가 MathTest로 불리는 경우 Google에서 내부 계수 배열에 액세스 할 수 있습니다 MathTest.Coefficients [i] 대신 MathTest [i]를 사용하십시오. http://stackoverflow.com/questions/1307354/c-sharp-indexer-usage 및 http://stackoverflow.com/questions/2185071/real-world-use-cases-for-c-sharp-indexers – ManoDestra

+1

이유 downvotes .. – PreqlSusSpermaOhranitel

+1

잘 모르겠다. 나는 널지지했다. 질문은 나에게 충분히 명확하게 보인다. 아마도 기본 언어 구문 질문이지만, 여전히 유효한 IMO 인 것처럼 다소 열악한 조사를 한 것 같습니다. – ManoDestra

답변

11

그것은 Indexer입니다.

인덱서를 사용하면 클래스 또는 구조체의 인스턴스를 배열처럼 인덱싱 할 수 있습니다. 인덱서는 접근자가 매개 변수를 사용한다는 점을 제외하고는 속성과 닮았습니다. 링크 된 MSDN에서

예 :

class SampleCollection<T> 
{ 
    // Declare an array to store the data elements. 
    private T[] arr = new T[100]; 

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)   
    public T this[int i] 
    { 
     get 
     { 
      // This indexer is very simple, and just returns or sets 
      // the corresponding element from the internal array. 
      return arr[i]; 
     } 
     set 
     { 
      arr[i] = value; 
     } 
    } 
} 

// This class shows how client code uses the indexer. 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // Declare an instance of the SampleCollection type. 
     SampleCollection<string> stringCollection = new SampleCollection<string>(); 

     // Use [] notation on the type. 
     stringCollection[0] = "Hello, World"; 
     System.Console.WriteLine(stringCollection[0]); 
    } 
} 
// Output: 
// Hello, World. 
2

List<T> 님의 myList[i]이 배열처럼 C#에서 어떻게 작동하는지 궁금한 적이 있습니까?

답변은 궁금한 점입니다. 게시 한 구문은 컴파일러가 get_Item(int index)set_Item(int index, decimal value)이라는 속성으로 변환하는 구문 설탕입니다. 이것은 예를 들어 List<T>에서 클래스에서 사용 된 내부 배열에 액세스하여 지정된 인덱스 (set 또는 get)에서 요소를 반환하는 데 사용됩니다. 이 기능을 Indexer이라고합니다.

오류 CS0082 :

public decimal get_Item(int i) 
{ 
    return 0; 
} 

당신은 컴파일러 오류 얻을 것이다 :

자신을, 같은 서명 방법을 만들려고하는지 테스트하려면 유형을 'MyClass에'이미 회원을 보유 동일한 매개 변수 유형이있는 'get_Item'

관련 문제