new 키워드를 사용하여 대리자를 인스턴스화하십시오. 대리자를 만들 때 새 식에 전달된 인수는 메서드 호출과 유사하게 작성되지만 메서드에 대한 인수는 없습니다.
예를 들어 -
public delegate void printString(string s); printString ps1 = new printString(WriteToScreen);
익명 메서드를 사용하여 대리자를 인스턴스화할 수도 있습니다.
//declare
delegate void Del(string str);
Del d = delegate(string name) {
Console.WriteLine("Notification received for: {0}", name);
}; 대리자를 선언하고 인스턴스화하는 예를 살펴보겠습니다.
예
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
} 출력
Value of Num: 35 Value of Num: 175