๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ/C#

[C#] ์ธ๋ฑ์„œ

by HanaV 2023. 8. 21.
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

"); wcs_do();