C# 언어 참조
delegate(C# 참조)
대리자 선언 형식은 다음과 같습니다.
public delegate void TestDelegate(string message);
delegate 키워드는 명명된 메서드나 무명 메서드를 캡슐화할 때 사용할 수 있는 참조 형식을 선언하는 데 사용됩니다. 대리자는 C++의 함수 포인터와 비슷하지만 형식 안전성과 보안성을 제공한다는 점이 다릅니다. 대리자 응용 프로그램에 대한 자세한 내용은 대리자 및 제네릭 대리자를 참조하십시오.
설명
대리자는 이벤트의 기반을 형성합니다.
대리자는 명명된 메서드나 무명 메서드와 연결하여 인스턴스화할 수 있습니다. 자세한 내용은 명명된 메서드 및 무명 메서드를 참조하십시오.
명명된 메서드와 함께 사용하려는 경우 허용 가능한 시그니처가 있는 메서드로 대리자를 인스턴스화해야 합니다. 메서드 시그니처에 허용되는 변동 범위에 대한 자세한 내용은 대리자의 공변성(Covariance)과 반공변성(Contravariance)을 참조하십시오. 무명 메서드와 함께 사용하는 경우 대리자 및 대리자와 연결된 코드가 함께 선언됩니다. 이 단원에서는 대리자를 인스턴스화하는 두 가지 방법을 모두 설명합니다.
using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
C# 언어 사양
자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.
-
1.11 대리자
-
15 대리자
참고 항목
참조
C# 키워드참조 형식(C# 참조)
무명 메서드(C# 프로그래밍 가이드)
개념
C# 프로그래밍 가이드대리자(C# 프로그래밍 가이드)
이벤트(C# 프로그래밍 가이드)
명명된 메서드(C# 프로그래밍 가이드)