산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# - 인덱서

인덱서 배열과 같은 객체를 인덱싱할 수 있습니다. 클래스에 대한 인덱서를 정의하면 이 클래스는 가상 배열과 유사하게 동작합니다. . 그런 다음 배열 액세스 연산자([ ])를 사용하여 이 클래스의 인스턴스에 액세스할 수 있습니다.

구문

1차원 인덱서는 다음 구문을 사용합니다. -

element-type this[int index] {

   // The get accessor.
   get {
      // return the value specified by index
   }
   
   // The set accessor.
   set {
      // set the value specified by index
   }
}

인덱서 사용

인덱서의 동작 선언은 속성과 어느 정도 유사합니다. 속성과 유사하게 get을 사용합니다. 및 설정 인덱서를 정의하기 위한 접근자. 그러나 속성은 특정 데이터 멤버를 반환하거나 설정하는 반면 인덱서는 개체 인스턴스에서 특정 값을 반환하거나 설정합니다. 즉, 인스턴스 데이터를 더 작은 부분으로 나누고 각 부분을 인덱싱하고 각 부분을 가져오거나 설정합니다.

속성을 정의하려면 속성 이름을 제공해야 합니다. 인덱서는 이름으로 정의되지 않지만 this 개체 인스턴스를 참조하는 키워드입니다. 다음 예는 개념을 보여줍니다 -

라이브 데모
using System;

namespace IndexerApplication {
   
   class IndexedNames {
      private string[] namelist = new string[size];
      static public int size = 10;
      
      public IndexedNames() {
         for (int i = 0; i < size; i++)
         namelist[i] = "N. A.";
      }
      public string this[int index] {
         get {
            string tmp;
         
            if( index >= 0 && index <= size-1 ) {
               tmp = namelist[index];
            } else {
               tmp = "";
            }
            
            return ( tmp );
         }
         set {
            if( index >= 0 && index <= size-1 ) {
               namelist[index] = value;
            }
         }
      }
      static void Main(string[] args) {
         IndexedNames names = new IndexedNames();
         names[0] = "Zara";
         names[1] = "Riz";
         names[2] = "Nuha";
         names[3] = "Asif";
         names[4] = "Davinder";
         names[5] = "Sunil";
         names[6] = "Rubic";
         
         for ( int i = 0; i < IndexedNames.size; i++ ) {
            Console.WriteLine(names[i]);
         }
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

오버로드된 인덱서

인덱서는 오버로드될 수 있습니다. 인덱서는 여러 매개변수를 사용하여 선언할 수도 있으며 각 매개변수는 다른 유형일 수 있습니다. 인덱스가 정수일 필요는 없습니다. C#에서는 인덱스가 문자열과 같은 다른 유형이 될 수 있습니다.

다음 예는 오버로드된 인덱서를 보여줍니다 -

라이브 데모
using System;

namespace IndexerApplication {
   class IndexedNames {
      private string[] namelist = new string[size];
      static public int size = 10;
      
      public IndexedNames() {
         for (int i = 0; i < size; i++) {
            namelist[i] = "N. A.";
         }
      }
      public string this[int index] {
         get {
            string tmp;
            
            if( index >= 0 && index <= size-1 ) {
               tmp = namelist[index];
            } else {
               tmp = "";
            }
            
            return ( tmp );
         }
         set {
            if( index >= 0 && index <= size-1 ) {
               namelist[index] = value;
            }
         }
      }
      
      public int this[string name] {
         get {
            int index = 0;
            
            while(index < size) {
               if (namelist[index] == name) {
                return index;
               }
               index++;
            }
            return index;
         }
      }

      static void Main(string[] args) {
         IndexedNames names = new IndexedNames();
         names[0] = "Zara";
         names[1] = "Riz";
         names[2] = "Nuha";
         names[3] = "Asif";
         names[4] = "Davinder";
         names[5] = "Sunil";
         names[6] = "Rubic";
         
         //using the first indexer with int parameter
         for (int i = 0; i < IndexedNames.size; i++) {
            Console.WriteLine(names[i]);
         }
         
         //using the second indexer with the string parameter
         Console.WriteLine(names["Nuha"]);
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2

C 언어

  1. C# Hello World - 첫 번째 C# 프로그램
  2. C# 키워드 및 식별자
  3. C# 변수 및 (기본) 데이터 형식
  4. C# 연산자
  5. C# 비트 및 비트 시프트 연산자
  6. C# 기본 입력 및 출력
  7. C# 식, 문 및 블록(예제 포함)
  8. C# 주석
  9. C# switch 문
  10. C# 삼항(? :) 연산자