c와 c++에는 함수포인터 라는 기능이 있다
#include<stdio.h>
//함수포인터는 반환형과 매개변수로 정의됨
void PrintHello()
{
printf("Hello\n");
}
void PrintWorld()
{
printf("World!\n");
}
int Sum(int _lhs, int _rhs)
{
return _lhs + _rhs;
}
int Sub(int _lhs, int _rhs)
{
return _lhs - _rhs;
}
void main()
{
//함수포인터(Function Pointer)
void (*pFunc)() = PrintHello; //반환형이 void고 매개변수가 없는 함수는 아무거나 들어 올 수 있다.
pFunc();
pFunc = PrintWorld;
pFunc();
int (*pCalc)(int, int) = Sum;
printf("Sum = %d\n", pCalc(2, 5));
pCalc = Sub;
printf("Sub = %d\n", pCalc(2, 5));
}
반환형 (포인터 함수)(매개변수) 를 선언하면
이 함수 포인터를 함수 전용 변수처럼 활용해서 함수를 담을 수 있는 기능이다.
c나 c++은 메모리를 직접 제어 가능하기에 이런 형태의 활용도 가능한 것이다
그런데 C#은 이런게 없다. 그래서 비슷한 동작을 위해 나온 것이 delegate(대리자)이다
class Program
{
//delegate(대리자)
public delegate void MethodDelegeate(); //C#의 함수포인터와 같은 것
static void PrintHello()
{
Console.WriteLine("hello");
}
static void PrintWorld()
{
Console.WriteLine("World");
}
static void Main()
{
//함수형을 쓰고 포인터를 만들지만 델리게이트는 자체가 형식, 이것 자체로 객체를 만듬
MethodDelegeate method = PrintHello;
method();
method = PrintWorld;
method();
}
}
델리게이트는 메서드(함수)를 참조할 수 있는 타입이다.
c나 c++의 함수포인터처럼 메서드를 변수처럼 다룰 수 있게 해준다.
'프로그래밍 언어 > C#' 카테고리의 다른 글
상속(2) - 결합도(Coupling)와 응집도(Cohesion) (0) | 2024.09.12 |
---|---|
Overloading 과 Overriding 그리고 다형성(Polymorphism) (1) | 2024.09.05 |
상속(Inheritance) (0) | 2024.09.05 |
생성자(Consturctor)와 소멸자(Destructor) (0) | 2024.09.05 |
객체 지향 프로그래밍(Object Oriented Programming) (2) | 2024.09.04 |