delegate는 메서드를 참조하는 데이터구조이다.

1
2
3
4
5
6
7
8
public delegate bool Judgement(int value);
 
Judgement judge = IsEven;
var count = Count(numbers, judge);
 
public bool IsEven(int n) {
    return n % 2 == 0;
}
cs


위와 같이 선언하면 인자로 int를 받고 return형이 bool인 메서드를 참조할 수 있게 된다.




익명 메서드는 위의 IsEven 메서드를 정의하지 않고 delegate 키워드를 사용해서 직접 정의한 것이다.

1
delegate(int n) { return n % 2 == 0; }
cs




인자를 받을 때에도 Predicate, Action, Func처럼 지정된 delegate를 사용하여도 된다.

1
public int Count(int[] numbers, Predicate<int> judge)
cs

Predicate - 인자값 1개, return값이 bool인 delegate

Action - 인자값 0~16, return값이 void

Func - 인자값 0~16, return형식 지정가능.




람다식

익명 메서드의 delegate 키워드를 없애고 => (람다 연산자)를 사용.

일종의 메서드라고 생각하면 된다. => 좌변은 인수선언. 우변은 메서드의 본문

1
var count = Count(numbers, n => n%2 == 0);
cs
1
var count = Count(numbers, n => n.ToString().Contains('1'));
cs




람다식을 이용하여 List<T> 클래스의 메서드 사용해보기

1
2
3
4
5
6
7
List<string> list = new List<string>();
 
var exists = list.Exists(s => s[0== 'A');
var name = list.Find(s => s.Length == 6);
var index = list.FindIndex(s => s.Contains("apple"));
list.ForEach(s => Console.WriteLine(s));
var lowerList = list.ConvertAll(s => s.ToLower());
cs


'프로그래밍 공부 > C#' 카테고리의 다른 글

기본 관용구  (0) 2019.01.11
LINQ  (0) 2019.01.11
인터페이스에 대해 프로그래밍하기  (0) 2019.01.11
Effective C#/ 제네릭 활용 - 아이템 18~23  (0) 2018.12.08
Effective C#/ .NET 리소스 관리 - 아이템 15~17  (0) 2018.12.07
Posted by misty_
,