๐ŸŽฎ Unity Study/C#

[C#] lambda์‹์ด๋ž€ ? ์–ธ์ œ ์‚ฌ์šฉํ• ๊นŒ ?

ibelieveinme 2023. 8. 17. 00:41
728x90

lambda ์‹ ? 

ํ•จ์ˆ˜์— ์ธ์ž๊ฐ’์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๋„ฃ๊ธฐ ์œ„ํ•ด, + ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ๋งŒ๋“  ๋ฌธ๋ฒ•.

lambad ์‹์€ ์„ ์–ธํ•œ ์ž๋ฆฌ์—์„œ'๋งŒ' ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ ‘๊ทผ์ง€์ •์ž, ๋ฐ˜ํ™˜๊ฐ’, ์ด๋ฆ„์ด ํ•„์š”์—†๋‹ค.

์žฌ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ํ˜ธ์ถœํ•ด์„œ ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•  ๋•Œ ํŽธ๋ฆฌํ•˜๋‹ค.

 

์œ„ ๊ฐœ๋…์„ ๋ฐ”ํƒ•์œผ๋กœ ์•„๋ž˜ ํ•จ์ˆ˜๋ฅผ lambda ์‹์œผ๋กœ ๋ฐ”๊ฟ”๋ณด์ž.

public void LambdaTest(){
	Debug.Log("LambdaTest");
}
() => { Debug.Log("LambdaTest"); }

 

์ธ์ž์™€ ๋ฐ˜ํ™˜๊ฐ’์ด ์žˆ๋Š” ํ•จ์ˆ˜๋Š” ์–ด๋–ป๊ฒŒ ๋ฐ”๊ฟ€๊นŒ

public int Add(int a, int b){
	return a + b;
}
(int a, int b) => { return a + b; }

 

์‚ฌ์šฉ์˜ˆ์‹œ๋ฅผ ์‚ดํŽด๋ณด์ž.

class Test {

    private void Start() {
        LambdaTest(() => {
            Debug.Log("Lambda Test");
        });
    }
    
    private void SayLambda() {
        Debug.Log("Lambda Test");
    }

    private void LambdaTest(Action action) {
        action();
    }
}

์œ„์™€ ๊ฐ™์ด LambdaTest ํ•จ์ˆ˜์— ํ•จ์ˆ˜๋ฅผ ๋„ฃ๊ณ ์ž ํ•  ๋•Œ, LambdaTest ํ•จ์ˆ˜์—๋Š” Action ์ด๋ž€ ์ธ์ž๋ฅผ ๋„ฃ๊ณ  ํ˜ธ์ถœ ์ชฝ์—์„œ๋Š” ๋žŒ๋‹ค์‹์„ ์ž‘์„ฑํ•˜๋ฉด ํŽธํ•˜๋‹ค. ๊ตฌ์ง€ SayLambda() ๋ผ๋Š” Debug ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•  ํ•„์š” ์—†๋‹ค๋Š” ๋œป.

728x90