갓똥
나는야 프로그래머
갓똥
전체 방문자
오늘
어제
  • 분류 전체보기 (186)
    • 프로그래밍 (146)
      • 자바 (9)
      • 안드로이드 (2)
      • 유니티 (20)
      • C++ (38)
      • C# (56)
      • HTML (2)
      • 파이썬 (3)
      • 자료구조 (2)
      • 알고리즘 (0)
      • 문제풀이 (4)
      • 디자인 패턴 (7)
      • 카카오톡 봇 (1)
      • 엑셀 (1)
      • 기타 (1)
    • 게임 (21)
      • 테일즈위버 (0)
      • 카이로소프트 (1)
      • 순위 (19)
      • 기타 (1)
    • 일상 (13)
      • 카페 (1)
      • 방탈출 (12)
    • 기타 (6)
      • 웃긴자료 (5)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 롤 골드그래프
  • pc 게임 순위
  • c# delegate
  • 유니티 그래프
  • 알고리즘
  • 전세계게임매출순위
  • c# 코루틴
  • c# collection
  • 게임 매출 순위
  • C++ 소멸자
  • C# boxing
  • 강남 방탈출
  • c# Thread
  • 모바일 게임 순위
  • C++ 상속
  • 유니티 그래프 그리기
  • c# unboxing
  • C++ virtual
  • C++
  • pc게임 순위
  • 유니티 골드그래프
  • Unity Graph
  • 전세계 게임 매출
  • 글로벌게임매출
  • 자바
  • 게임 디자인 패턴
  • 게임매출순위
  • C# 예외 처리
  • c# coroutine
  • 2020년 게임 매출

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갓똥

나는야 프로그래머

[C#] 인덱서 (Indexer)
프로그래밍/C#

[C#] 인덱서 (Indexer)

2020. 3. 19. 17:08
728x90
반응형

1. 핵심 정리

using System;

class Sentence {
    private string[] words = null;
    
    public Sentence(string s) { words = s.Split(); }
}

class Program {
    public static void Main() {
        Sentence s = new Sentence("Dog is Animal");
        
        s[0] = "Cat";
        
        Console.WriteLine(s[0]); // Cat
        Console.WriteLine(s);    // Cat is Animal
    }
}

 ① 객체를 배열 처럼 사용할 수 있게 하는 문법

    => C++에서 [ ] 연산자 재정의

    => 속성(Property)와 유사한 문법

 

using System;

class Sentence {
    private string[] words = null;
    
    public Sentence(string s) { words = s.Split(); }
    
    // public string Name { get; set; } - 속성
    public string this[int idx] {    // - 인덱서
        get { return words[idx]; }
        set { words[idx] = value; }
    }
}

class Program {
    public static void Main() {
        Sentence s = new Sentence("Dog is Animal");
        
        s[0] = "Cat";
        
        Console.WriteLine(s[0]);
        Console.WriteLine(s);
    }
}

 ② Property vs Indexer

위의 코드에서 이제 s[0]은 제대로 출력되는 걸 확인할 수 있다.
하지만 s는 사용자 정의 타입이므로 tostring을 재정의 하지 않으면 클래스 이름이 나온다.
s를 원하는 의도대로 출력이 되게 하려면 ToString()을 재정의 해야 한다.
using System;

class Sentence {
    private string[] words = null;
    
    public Sentence(string s) { words = s.Split(); }
    
    // public string Name { get; set; } - 속성
    public string this[int idx] {    // - 인덱서
        get { return words[idx]; }
        set { words[idx] = value; }
    }
    
    public override string ToString() {
        return string.Join(" ", words);
    }
}

class Program {
    public static void Main() {
        Sentence s = new Sentence("Dog is Animal");
        
        s[0] = "Cat";
        
        Console.WriteLine(s[0]);
        Console.WriteLine(s);
    }
}

 


2. 인덱서의 원리

using System;

class Sentence {
    private string[] words = null;
    public Sentence(string s) { words = s.Split(); }
    
    // property
    public string Name { get; set; } = "UNKNOWN";
    
    // indexer
    public string this[int idx] {
        get { return words[idx]; }
        set { words[idx] = value; }
    }
}

class Program {
    public static void Main() {
    
    }
}

ILDSM으로 확인해보면 get과 set이 두 쌍 있는 것을 확인할 수 있다.
Name과 Item으로 있는데
Name은 파라미터가 하나인데
Item은 int로 하나가 더 있는 것을 볼 수 있다.
int는 idx로 Item이 인덱서이다.

 

 ① Property vs Indexer

 

 ② 인덱서(indexer)는 매개 변수를 가지는 속성(Property) 이다.

 


3. 주의 사항

using System;

class Sentence {
    public int this[int idx]    { get { return 0; } }
    public int this[string idx] { get { return 0; } }
    public int this[int idx, int idx2]    { get { return 0; } }
    public int this[int idx, string idx2] { get { return 0; } }
}

class Program {
    public static void Main() {
        Sentence s = new Sentence(); 
        
        int n1 = s["A"];
        int n2 = s[0, 1];
        int n3 = s[0, "A"];
    }
}

 ① Index의 타입이 반드시 정수일 필요는 없다.

 

 ② 2개 이상의 index 값도 가질 수 있다.

728x90
반응형

'프로그래밍 > C#' 카테고리의 다른 글

[C#] 제너릭 제약 (Generic Constraint)  (0) 2020.03.27
[C#] 제너릭 (Generic)  (0) 2020.03.23
[C#] 속성 (Property) (2)  (0) 2020.03.13
[C#] 속성 (property) (1)  (0) 2020.03.12
[C#] Extension Method  (0) 2020.03.09
    '프로그래밍/C#' 카테고리의 다른 글
    • [C#] 제너릭 제약 (Generic Constraint)
    • [C#] 제너릭 (Generic)
    • [C#] 속성 (Property) (2)
    • [C#] 속성 (property) (1)
    갓똥
    갓똥
    공부하며 알아가는 내용을 정리해 봅니다.

    티스토리툴바