개발공부/C#

[C#] 인덱서(Indexer)

정보를드립니다 2019. 10. 18. 20:19
반응형

C# 인덱서(Indexer)
C# 인덱서(Indexer)는 클래스나 구조체의 데이터를 배열처럼 인덱스로 접근이 가능하도록 구현을 할 수 있게 합니다.

정의 
this[]를 사용하여 속성처럼 get과 set으로 정의합니다.

 

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class AAAA
    {
        private int[] num = new int[10];
        public int this[int nIndex]
        {
            get
            {
                if (nIndex < 0 || nIndex > 10)
                {
                    throw new IndexOutOfRangeException();
                }
                else
                {
                    return num[nIndex];
                }
            }
            set
            {
                if (nIndex < 0 || nIndex > 10)
                {
                    throw new IndexOutOfRangeException();
                }
                else
                {
                    num[nIndex] = value;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            AAAA aaaa = new AAAA();
            aaaa[0= 2;
            Console.WriteLine(aaaa[0]);
        }
    }
}
 
 

위와 같이 클래스에 배열변수를 인덱서를 이용해서 접근해서 get / set이 가능하도록 만들 수 있습니다.


C# 6(Visual Studio 2015)부터는 이 구문 대신


public int this[int nIndex] => num[nIndex];

이렇게 표현할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public int this[int nIndex]
{
    get
    {
        if (nIndex < 0 || nIndex > 10)
        {
            throw new IndexOutOfRangeException();
        }
        else
        {
            return num[nIndex];
        }
    }
    set
    {
        if (nIndex < 0 || nIndex > 10)
        {
            throw new IndexOutOfRangeException();
        }
        else
        {
            num[nIndex] = value;
        }
    }
}
 
s

 

C# 7.0(Visual Studio 2017)부터 get 및 set 접근자 모두 본문 멤버로 구현할 수 있습니다.

1
2
3
4
5
public T this[int nIndex]
{
    get => num[nIndex]; 
    set => num[nIndex] = value; 
}
 
반응형