728x90
์ธ๋ฑ์(Indexer)๋ ๊ฐ์ฒด ๋ด์ ๋ฐ์ดํฐ๋ฅผ ์ธ๋ฑ์ค๋ฅผ ์ฌ์ฉํ์ฌ ์ ๊ทผํ๋ ๋ฐ ์ฌ์ฉ๋๋ค. ์ธ๋ฑ์๋ฅผ ํตํด ๊ฐ์ฒด์ ๋ด๋ถ ๋ฐ์ดํฐ๋ ์์์ ๋ฐฐ์ด์ฒ๋ผ ์ธ๋ฑ์ค๋ฅผ ์ฌ์ฉํ์ฌ ์ ๊ทผํ ์ ์์ด์ ๋ฐฐ์ด์ฒ๋ผ ์ฌ์ฉํ ์ ์๋ค.
์ธ๋ฑ์๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์๋์ ๊ฐ์ ํํ๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
public returnType this[parameterType parameter]
{
get { /* ์ธ๋ฑ์ค๋ฅผ ํตํ ๊ฐ ๋ฐํ */ }
set { /* ์ธ๋ฑ์ค๋ฅผ ํตํ ๊ฐ ์ค์ */ }
}
์๋๋ ์ธ๋ฑ์๋ฅผ ์ฌ์ฉํ ๊ธฐ๋ณธ ์์์ด๋ค.
class SampleCollection
{
private string[] data = new string[2];
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
class Program
{
static void Main()
{
SampleCollection collection = new SampleCollection();
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // "Hello"
Console.WriteLine(collection[1]); // "World"
}
}
ํ์ฌ ์ธ๋ฑ์๋ฅผ ์ํด ๋ง๋ค์ด์ง ๋ฐฐ์ด์ ๊ธธ์ด๋ 3์ด๋ค. ์ฆ, collection[10]์ ํ๊ฒ ๋๋ฉด index out of boundary ์๋ฌ๊ฐ ๋๊ฒ ๋๋ค. ์ด๋ด ๋๋ฅผ ๋๋นํด์ set ๋ถ๋ถ์ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ์ฌ์กฐ์ ํ๋ ์ฝ๋๋ฅผ ์ถ๊ฐํ์๋ค.
class CustomCollection
{
private string[] data = new string[2];
public string this[int index]
{
get { return data[index]; }
set
{
if (index >= data.Length)
{
Array.Resize(ref data, index+1);
Console.WriteLine("๋ฐฐ์ด ๊ธธ์ด ์ฆ๊ฐ");
}
data[index] = value;
}
}
}
class Program
{
static void Main()
{
CustomCollection collection = new CustomCollection();
collection[0] = "Item 1";
collection[1] = "Item 2";
collection[2] = "Item 3"; // ๋ฐฐ์ด ๊ธธ์ด๊ฐ ์ฆ๊ฐ๋๊ณ ๋ฐ์ดํฐ๊ฐ ๋ค์ด๊ฐ
collection[3] = "Item 4"; // ๋ฐฐ์ด ๊ธธ์ด๊ฐ ์ฆ๊ฐ๋๊ณ ๋ฐ์ดํฐ๊ฐ ๋ค์ด๊ฐ
Console.WriteLine(collection[0]); // "Item 1"
Console.WriteLine(collection[1]); // "Item 2"
Console.WriteLine(collection[2]); // "Item 3"
Console.WriteLine(collection[3]); // "Item 4"
}
}
728x90
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C#] ์ผ๋ฐํ ํ๋ก๊ทธ๋๋ฐ: ๋ฉ์๋, ํด๋์ค, ์ ์ฝ์กฐ๊ฑด (0) | 2023.08.22 |
---|---|
[์ด๊ฒ์ด C#์ด๋ค] Chapter10: ์ฐ์ต๋ฌธ์ (0) | 2023.08.21 |
[C#] Collection (0) | 2023.08.21 |
[C#] ์ด์ฐจ์ ๋ฐฐ์ด๊ณผ ๊ฐ๋ณ ๋ฐฐ์ด (0) | 2023.08.21 |
[C#] ๋ฐฐ์ด ๋ค๋ฃจ๊ธฐ (0) | 2023.08.21 |