3. Implementation/C#

C# Delegate 사용하기

SSKK 2010. 3. 26. 01:13
Delegate 도 클래스와 마찬가지로 두가지 단계를 거친다.

1. Delegate 정의 (변수 선언이 아님을 주의하자!)

delegate void VoidOperation(uint x);
delegate double TwoLongsOp(long L1, long L2);
delegate string GetAsString();
public delegate string GetAsString();

2. Delegate의 인스턴스 생성

 static void Main(string[] args)
{
    int X = 40;
    GetAsString FirstStringMethod = new GetAsString(X.ToString);  // 메소드를 파라미터로 전달
    Console.WriteLine("String is" + FirstStringMethod());
}

  • Delegate 는 형식 안전하므로 호출되는 메소드의 signature 가 제대로 되었다는 것이 보장된다.
  • 메소드가 정적 메소드 혹은 인스턴스 메소드인지 신경쓰지 않는다.
3. Multicast Delegate

+, -, -=, += 의 연산자를 이용하여 Delegate 를 추가/삭제 할 수 있으며, void 형으로 선언한다.

delegate void DoubleOp(double value);

class MathOperations
{
    public static void MultiplyByTwo(double value)
    {
        double result = value*2;
        Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);
    }

    public static void Squre(double value)
    {
        double result = value*value;
        Console.WriteLine("Squaring: {0} gives {1}", value, result);
    }
}
static void Main(string[] args)
{
    DoubleOp operations = new DoubleOp(MathOperations.MultiplyByTwo);
    operations += new DoubleOp(MathOperations.Square);

    ProcessAndDisplayNumber(operations, 2.0);
    ProcessAndDisplayNumber(operations, 7.94);
    Console.WriteLine();
}

참고 : Professional C# - 정보 문화사