Closure

์˜ˆ์‹œ

case 1

public void Test1()
{
    Action print = delegate()
    {
        Console.WriteLine("A");
    };
    print();
}
  • print๋ผ๋Š” delegate ๊ฐ์ฒด์— ๋ฌด๋ช… ๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•˜๊ณ  ํ• ๋‹น
  • ์ด๊ฒƒ์€ Closure๊ฐ€ ์•„๋‹ˆ๋‹ค

case 2

public void Test2()
{            
    Action<string> print = delegate (string msg)
    {                
        Console.WriteLine(msg);
    };
    print("A");
}
  • print๋ผ๋Š” delegate ๊ฐ์ฒด์— ํŒŒ๋ผ๋ฏธํ„ฐ(string msg)๋ฅผ ๋ฐ›๋Š” ๋ฌด๋ช… ๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•˜๊ณ  ํ• ๋‹น
  • ์ด๊ฒƒ๋„ Closure๊ฐ€ ์•„๋‹ˆ๋‹ค

case 3

public void Test3()
{
    int key = 10;

    Action<string> print = delegate (string msg)
    {
        string str = key + msg;
        Console.WriteLine(str);
    };

    print("A");  // 10A
}
  • delegate์— ํ• ๋‹นํ•  ๋ฉ”์„œ๋“œ์˜ ์™ธ๋ถ€ ๋ณ€์ˆ˜, Test3์˜ ์ง€์—ญ ๋ณ€์ˆ˜์ธ key๋ฅผ ์‚ฌ์šฉ
  • ์ด๊ฒƒ์ด Closure์˜ ์˜ˆ์‹œ

Clusore๋ž€?

  • ์–ด๋–ค ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ๊ณ , ๊ทธ ๋ฉ”์„œ๋“œ ์•ˆ์—์„œ ๋ฌด๋ช… ๋ฉ”์„œ๋“œ๋‚˜ ๋žŒ๋‹ค์‹์ด ์ •์˜๋˜์–ด ์žˆ๊ณ  ์ง€์—ญ ๋ณ€์ˆ˜๊ฐ€ ์„ ์–ธ๋˜์–ด ์žˆ๋‹ค
    • ์ด ๋•Œ ์ •์˜๋œ ๋ฌด๋ช… ๋ฉ”์„œ๋“œ ํ˜น์€ ๋žŒ๋‹ค์‹์ด ์ด ์ง€์—ญ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ด๋ฅผ Clousre๋ผ ํ•œ๋‹ค
  • ์™ธ๋ถ€ ํ•จ์ˆ˜์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ๋‚ด๋ถ€ ํ•จ์ˆ˜ ํ˜น์€ ์ด๋Ÿฌํ•œ ์›๋ฆฌ
    • ์ผ๋ฐ˜์ ์œผ๋กœ ์–ด๋–ค ํ•จ์ˆ˜๊ฐ€ ์†Œ๋ฉธํ•˜๋ฉด์„œ ์Šคํƒ ํ”„๋ ˆ์ž„์ด ํ•ด์ œ๋˜์ง€๋งŒ, ์™ธ๋ถ€ํ•จ์ˆ˜์˜ ์ง€์—ญ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋‚ด๋ถ€ ํ•จ์ˆ˜๊ฐ€ ์†Œ๋ฉธํ•  ๋•Œ๊นŒ์ง€ ์™ธ๋ถ€ํ•จ์ˆ˜๋Š” ์†Œ๋ฉธํ•˜์ง€ ์•Š์Œ
  • Lexcial scope๋‚ด์˜ Free variable์„ ์‚ฌ์šฉํ•˜๋Š” ์ผ๊ธ‰ํ•จ์ˆ˜(First-class function)
  • ํ•จ์ˆ˜๊ฐ€ Context๋ฅผ ๋ณด์œ ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ ๊ธฐ๋Šฅ
    • ์—ฌ๊ธฐ์„œ Context๋Š” Closure๊ฐ€ ์ •์˜๋œ ์™ธ๋ถ€ ํ•จ์ˆ˜์˜ ๋ณ€์ˆ˜๋“ค

์ผ๊ธ‰ํ•จ์ˆ˜

  • ๋‹ค๋ฅธ ๋ฉ”์„œ๋“œ/ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
  • C#์—์„œ์˜ ๋ฌด๋ช…๋ฉ”์„œ๋“œ, ๋žŒ๋‹ค์‹ ๋“ฑ
    • Action, Predicate, Func, delegate ๋“ฑโ€ฆ

์–ด๋””์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฐ€?

  • ํ•จ์ˆ˜์˜ ์ฒซ ์ •์˜ ์‹œ์ ์—์„œ์˜ Context๋ฅผ ์œ ์ง€ํ•  ํ•„์š”๊ฐ€ ์žˆ์„ ๋•Œ
class Class1
{
    private List<string> list = new List<string>()
    {
        "A", "AB", "ABC", "ABCD", "ABCDE"
    };

    public IList<string> GetList(int maxLength)
    {
        // Where์— ํ• ๋‹น๋˜๋Š” ํ•จ์ˆ˜๋Š” ์™ธ๋ถ€ ๋ณ€์ˆ˜์ธ maxLength๋ฅผ ์‚ฌ์šฉ
        // ์•„๋ž˜ ๋žŒ๋‹ค์‹์€ Closure
        var limitedList = list.Where(p => p.Length <= maxLength).ToList();

        return limitedList;
    }
}

์ถœ์ฒ˜

Categories: ,

Updated: