2014년 2월 19일 수요일

29. [C#,닷넷교육,인덱서]C# 인덱서(C# Indexer,Property),C#/닷넷/ASP/ADO.NET/닷넷교육잘하는곳/닷넷개발자교육/C#ASP/C#네트워크 인덱서(Indexer)란:

29. [C#,닷넷교육,인덱서]C# 인덱서(C# Indexer,Property),C#/닷넷/ASP/ADO.NET/닷넷교육잘하는곳/닷넷개발자교육/C#ASP/C#네트워크   인덱서(Indexer)란:
 
인덱서(Indexer):namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
인덱서(Indexer)는 인덱스를 이용하여 객체내의 데이터에 접근하게 해주는 프로퍼티라고 생각하면 된다. 객체를 배열처럼 접근 할 수 있는 방법을 제공 한다. 사용법이 배열과 비슷하다는 의미이지 실제로 객체를 배열로 쓴다는 의미는 아니다.
 
인덱서와 프로퍼티의 비교
 
프로퍼티가 이름을 통해 객체내의 데이터에 접근하게 해 준다면 인덱서는 인덱스를 통해 객체내의 데이터에 접근하게 해 준다. 인덱서는 get, set 접근자를 통해 어떤 필드의 값을 얻어 오거나 어떤 계산을 통해 새로운 값을 다른 곳에 지정한다. 인덱서 역시 프로퍼티 처럼 실제 값을 가지고 있지 않기 때문에 ref, out과 같은 접근자를 사용 할 수 없다. 물론 둘 다 void는 사용 할 수 없다.
 
System.String 클래스에 잠시 살펴보자.
 
string s = “Hello”;
char c = s[0];   //c = ‘H’
 
s가 배열이 아님에도 불구하고 배열처럼 사용하고 있다. 이것은 String 클래스가 인덱서로 구현되어 있기 때문에 가능 한 것이다. 인덱서를 사용하면 string 타입처럼 객체를 배열처럼 쓰는 것이 가능해 진다는 것이다.
 
s[2] = ‘c’; //에러
 
이 경우 오류가 발생 하는 것은 String 인덱서가 읽기 전용으로 만들어 졌기 때문이며 인덱서를 이용하면 r-value 이든 l-value 이든지 상관없이 배열처럼 이용 할 수 있다.
 
[예제1]
using System;
 
public class Animation
{
       private int total;           //총 애니메이션 편수
       private string[] title;      //각 볼륨당 제목
       private string distributor;  //유통사
       private string date;         //제작날짜
       private int price;           //가격
 
       public Animation(int total, string distributor, string date, int price)
       {
             this.total = total;
             this.title = new string[total];
             this.distributor = distributor;
             this.date = date;
             this.price = price;
       }
 
       //볼륨의 제목 설정
       public void setTitle(int number, string title)
       {
             this.title[number] = title;
       }
 
       //볼륨의 제목을 얻어오는메소드
       public string getTitle(int number)
       {
             return title[number];
       }
 
       //제작사 정보를 읽어옴
       public string getDistributor()
       {
             return distributor;
       }
 
       //가격 정보를 읽어옴
       public int getPrice()
       {
             return price;
       }
 
       //총애니메이션의 수를 알아내는 메소드
       public int getTotal()
       {
             return total;
       }
}
 
class AniTest
{     
       static void :namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />Main()
       {
             Animation ani = new Animation(5, "한국애니","10-27-2004", 35000);
             ani.setTitle(0, "인어공주");
             ani.setTitle(1, "신데렐라");
             ani.setTitle(2, "백설공주");
             ani.setTitle(3, "바보온달");
             ani.setTitle(4, "라이온킹");
 
             Console.WriteLine("배급사: {0}", ani.getDistributor());
             Console.WriteLine("가격: {0}", ani.getPrice());
             Console.WriteLine("----------------------------");
 
             for(int i=0; i < ani.getTotal(); i++)
             {
                    Console.WriteLine("Volume{0} : {1}", i, ani.getTitle(i));
             }           
       }
}
 
위 예문에서의 ani.setTitle(0, "인어공주"); 부분은 인덱서를 이용하면 ani[0] = “인어공주로 표현이 가능하다. ani가 배열은 아니지만 배열 처럼 사용이 가능 하다는 것이다인덱서를 사용하는 방법은 프로퍼티를 쓰는 방법과 유사하다. get, set 접근자를 가지고 있으며 인덱서인 경우엔 별도의 이름은 없다. 다른 필드처럼 인스턴스 뒤에 점을 사용하지 않고 바로 그 클래스 자체가 배열이 되기 때문에 this 키워드가 인덱서의 이름으로 사용된다. 위의 예제를 인덱서를 사용한 형태로 바꾸면 다음과 같다.
 
using System;
 
public class Animation
{
       private int total;           //총 애니메이션 편수
       private string[] title;      //각 볼륨당 제목
       private string distributor;  //유통사
       private string date;         //제작날짜
       private int price;           //가격
 
       public Animation(int total, string distributor, string date, int price)
       {
             this.total = total;
             this.title = new string[total];
             this.distributor = distributor;
             this.date = date;
             this.price = price;
       }
 
       //이부분에서 인덱서를 정의 한다. 이전 프로그램의 setTitle, getTitle이 인덱서로 대체됨, 결국 this라는 Property가 인덱서인 것이다.
       public string this[int index]
       {
             get
             {
                    return title[index];
             }
 
             set
             {
                    title[index] = value;
             }
       }
 
      
       //제작사 정보를 읽어옴
       public string getDistributor()
       {
             return distributor;
       }
 
       //가격 정보를 읽어옴
       public int getPrice()
       {
             return price;
       }
 
       //총애니메이션의 수를 알아내는 메소드
       public int getTotal()
       {
             return total;
       }
}
 
class AniTest
{     
       static void Main()
       {
             Animation ani = new Animation(5, "한국애니","10-27-2004", 35000);
             ani[0]="인어공주";
             ani[1]="신데렐라";
             ani[2]="백설공주";
             ani[3]="바보온달";
             ani[4]="라이온킹";
 
             Console.WriteLine("배급사: {0}", ani.getDistributor());
             Console.WriteLine("가격: {0}", ani.getPrice());
             Console.WriteLine("----------------------------");
 
             for(int i=0; i < ani.getTotal(); i++)
             {
                    Console.WriteLine("Volume{0} : {1}", i, ani[i]);
             }           
       }
}
 
 
인덱서(Indexer) 와 배열(Array)의 비교
 
1.  인덱서는 배열의 표기법과 비슷하다. 하지만 배열은 integer 형으로만 첨자를 사용 가능 하지만 인덱서인 경우엔 다른 타입도 첨자로 사용 가능 하다.
 
class test {
public string this[string index]
{
       get {…}
       set {…}
}
}
 
2.  또한 인덱서는 오버로딩이 가능 하다. 여러 개의 인덱서를 선언 해 놓고 그곳의 인자가 다르면 오버로딩 된다.
 
class test {
    public string this[int number] { }
    public string this[int number, string name] {}
}

C#4.0, ADO.NET, Network 프로그래밍 5일 35시간   02-24
C#,ASP.NET마스터 18일 54시간   03-03
닷넷실무자를위한WPF개발자과정 8일 56시간   02-29
C#,ASP.NET마스터 8일 56시간   03-09


댓글 없음:

댓글 쓰기