티스토리 뷰
C#에서 delegate는 C++의 함수포인터와 유사한 역할을 하는 메소드를 대신하여 호출하는 변수이다.
delegate로 메소드를 호출하려면 함수를 선언하듯이 동일한 파라미터와 리턴타입을 가지도록 선언하면 된다. 그리고 선언한 delegate 타입의 변수를 생성하고 new 키워드를 써서 delegate 객체를 생성하여 메소드를 참조 시킨다.
delegate int MyDelegate(int a);
Mydelegate del_func;
del_func = new MyDelegate(func);
public static int func(int n) { ... };
delegate는 메소드를 호출할 때 파라미터 내의 또 다른 메소드를 호출하는 Callback 메소드를 구현할 때 의미가 있다.
delegate int MyDelegate(int a, int b);
class MainApp
{
public static void Calculator(int a, int b, MyDelegate del)
{
Console.WriteLine( dele(a,b) );
}
public static int Plus(int a, int b) { return a+b; }
public static int Minus(int a, int b) { return a-b; }
static void Main(string[] args)
{
MyDelegate del_plus = new MyDelegate(Plus);
MyDelegate del_minus = new MyDelegate(Minus);
Calculator(1, 3, del_plus);
Calculator(4, 2, del_minus);
}
}
delegate는 +나 += 연산자로 여러개의 메소드를 참조할 수 있다. 여러개의 delegate를 호출하면 참조 된 메소드가 차례대로 호출이 된다. 이것을 delegate chain이라 한다.
delegate는 함수 포인터와 닮았지만 C에서의 함수 포인터는 외부 함수의 주소값만을 가지지만 delegate는 클래스 객체의 주소와 메소드 주소를 함께 가지고 있다. 클래스의 멤버 함수에 대한 포인터로 객체에 대한 컨텍스트를 가지는 C++의 멤버 함수 포인터(Point to member function)와 비슷하지만 선언 시 특정 클래스만 지정할 수 있다는 한계가 있다.
event는 클래스 내의 필드처럼 정의 되어 이벤트가 일어났음을 외부의 이벤트 가입자(subscriber)들에게 알려준다.
이벤트가 발생했을 때 어떤 명령들을 실행할 지 이벤트 핸들러를 통해 정해 준다. delegate와 같이 += 연산자로 추가할 수 있다.
delegate는 외부에서 객체를 호출할 수 있어 콜백용도로 사용하고 event는 public으로 되어 있어도 클래스 외부에서는 호출이 불가능 하고 객체의 상태변화나 사건 발생 용도로 구분해서 사용한다.
namespace EventTest
{
delegate void EventHandler(string msg);
class MyNotifier
{
public event EventHandler SomethingHappend;
public void DoSomething(int number)
{
int temp = num % 10;
if(temp != 0 && temp % 3 == 0)
{
SomethingHappend(String.Format("{0} : Even", num));
}
}
}
class Program
{
static public void MyHandler(string msg)
{
Console.WriteLine(msg);
}
static void Main(string[] args)
{
MyNotifier notifier = new MyNotifier();
notifier.SomethingHappened += new EventHandler(MyHandler);
for(int i=1 ; i<30 ; i++)
{
notifier.DoSomething(i);
}
}
}
}
www.csharpstudy.com/CSharp/CSharp-delegate-concept.aspx
'OOP > C#' 카테고리의 다른 글
delegate 대리자 (0) | 2025.02.12 |
---|---|
자료형 Data type (0) | 2025.02.03 |
6. C# 메소드 (0) | 2021.01.13 |
5. C# Exception (0) | 2021.01.11 |
4. C# foreach문, yield (0) | 2021.01.10 |
- Total
- Today
- Yesterday
- trailing return type
- C#
- delegate
- emplace
- 카카오코딩테스트
- 문자열정수변환
- C++
- range based for
- initializer_list
- 빌더패턴
- 힙영역
- UnionFind
- unity6
- STL컨테이너
- Event
- STL
- 유니티기초
- Algorithm
- 알고리즘
- dfs
- 프로그래머스
- 유니티6
- 스택영역
- 이진 변환 반복하기
- modern C++
- 유니온파인드
- ModernC++
- 유니티
- 코딩테스트
- 팩토리메서드패턴
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |