프로그래밍/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
반응형