using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _11
{
class TestInt
{
private int[] _array = new int[6]; //6개 짜리 배열
public int this[int Index] //인덱서 Indexer
{
get //가져갈때
{
return _array[Index];
}
set //대입
{
_array[Index] = value;
}
}
}
class Test
{
private string[] _array = new string[5];
public string this[int Index]
{
get
{
return _array[Index];
}
set
{
_array[Index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Test aTest = new Test();
TestInt aTestInt = new TestInt();
aTest[0] = "할룽a";
aTest[1] = "할룽b";
aTest[2] = "할룽c";
aTest[3] = "할룽d";
aTest[4] = "할룽e";
Console.WriteLine(aTest[2]);
aTestInt[0] = 1;
aTestInt[1] = 2;
aTestInt[2] = 3;
aTestInt[3] = 4;
aTestInt[4] = 5;
aTestInt[5] = 6;
Console.WriteLine(aTestInt[5]);
}
}
}
출력 결과
aTest[2] = "할룽c"를 넣게 되면 위에 public int this[int Index]로 가게 되어 입력하는 곳인 set으로 들어가게 된다.
aTestInt[5] 콘솔로 호출하게 되면 public int this[int Index]로 가게 되어 입력하는 곳인 get으로 들어가게 된다.
이렇게 쓰는것은 C#에서만 사용하는 방법이다
보통의 경우에는 메소드를 만들어서 사용하게 된다. get이랑 set를 따로 만들어 사용한다.
array[]의 길이를 정해두고 사용하는것이 아니라 변하게 사용하고 싶으면 위에와 같이 사용하면 된다
따로 메소드를 두어 size의 변화를 주면 된다. 메소드는 public으로 한다.
'스마트팩토리 > C#' 카테고리의 다른 글
2020/07/27 C# (0) | 2020.07.27 |
---|---|
2020/07/23~24 C# (0) | 2020.07.23 |
2020/07/15 C# (0) | 2020.07.15 |
2020/07/01 C# (0) | 2020.07.01 |
2020/06/30 C# (0) | 2020.06.30 |