본문 바로가기

C#

람다

이름이 없는 메서드.

즉석에서 구현할 수 있음

대충 한 줄 짜리 함수 만들기 아까울 때 쓰면 될 듯

 

 

형식

(     ) => {      };

(매개변수들..) => { 리턴 타입에 맞는 값 } ;

 

 

예시

onAction += () => Debug.Log("처리A");

 

오버라이딩 가능성 있을 경우 X..

3줄 이상 돼도 X..

가독성 떨어짐

 

예시

private int health = 0;

public void RestoreHealth(int amount) {
	health += amount;
}

public bool IsDead() {
	return (health <= 0);
}

↓↓↓

private int health = 0;

public void RestoreHealth(int amount) => health += amount;
public bool IsDead() => (health <= 0);

 

 

private int health = 0;

public int Health {
	get { return health; }
	set { health = value; }
}

public bool IsDead {
	get { return (health <= 0); }
}

↓↓↓

 

private int health = 0;

public int Health {
	get => health;
	set => health = value;
}

public bool IsDead => (health <= 0);

 

 

즉석밥마냥 즉석에서 함수를 만든다는 느낌

void Start()

{

onHit += () => {

                       Debug.Log("람다 처리1");

                       Debug.Log("람다 처리2");

                        };

}

출력시

 

람다 처리1

람다 처리2

 

이렇게 나온다.

'C#' 카테고리의 다른 글

프로퍼티  (0) 2022.06.21
전략적 패턴  (0) 2022.06.20
Event  (0) 2022.06.20
Delegate - Action, Func  (0) 2022.06.20
Delegate  (0) 2022.06.17