2015-01-02 17 views
1

이 가능한 유형을 어떻게 만들 것인지 알고 싶습니다. 아이디어는 단지 3 원소의 정수 배열을 나타내는 형식을 가지지 만 일반 배열과 마찬가지로 대괄호를 사용하여 액세스 할 수 있습니다. 나는 기본적으로설정된 수의 요소가있는 기본 유형의 배열을 항상 나타 내기 위해 사용자 지정 형식을 만들려면 어떻게해야합니까?

myType myArray = new myType(); 

는 다음과 같은 myArray의 액세스

int[] myArray = new int[3]; 

로 변환 꿔

단지가 사용하여 생성 된 경우 같은 원래 INT [] 공정 :

myArray[0] = 1; 
myArray[1] = 2; 
myArray[2] = 3; 

이것도 가능합니까?

+0

왜 이렇게하고 싶습니까? List 제네릭 유형을 사용한 적이 있습니까? 또한 인덱서를 사용하여 요소에 액세스 할 수 있습니다. –

+2

모든 개체에 인덱서를 추가 할 수 있습니다. http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx – David

+0

@david에서 설명한 것처럼 색인 생성기'myArray' http://www.c-sharpcorner.com/uploadfile/vivek4u_swamy/indexers-and-properties/ – geedubb

답변

2

모든 개체에 add an 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; 
     } 
    } 
} 

개체는 내부적으로 100 개의 요소 배열을 관리합니다. 귀하의 경우에는 3 가지 요소 만 사용하면됩니다. 해당 객체의 사용은 당신이 찾고있는 무엇을 닮은 것 : 인덱서가 명시 적으로 예에 int으로 정의된다

// 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]); 

참고도있다. 인덱서에는 다른 유형도 사용할 수 있습니다. (string은 일반적인 대안입니다.)

+0

생성자가 유용합니다 : 'public SampleCollection (int 용량) { arr = new T [capacity]; }' – khlr

+0

@ khlr : OP가 용량 코드를 정의하기 위해 소비 코드를 원할 경우. 반면에, OP가 내부적으로 * 항상 * 3 요소 배열을 만드는 사용자 정의 객체를 원한다면, 아니오. – David

+0

맞습니다. 나는이 샘플에 왜 100을 넣었는지 궁금해했다. – khlr