다음을 통해 공유


방법: 대리자 조합(멀티캐스트 대리자)(C# 프로그래밍 가이드)

업데이트: 2010년 9월

이 예제에서는 멀티캐스트 대리자를 만드는 방법에 대해 설명합니다. 대리자 개체에는 + 연산자를 사용하여 대리자 인스턴스에 여러 개체를 할당할 수 있는 유용한 특성이 있습니다. 멀티캐스트 대리자에는 할당된 대리자 목록이 포함됩니다. 멀티캐스트 대리자를 호출하면 목록에 있는 대리자가 순서대로 호출됩니다. 같은 형식의 대리자만 조합할 수 있습니다.

- 연산자를 사용하면 멀티캐스트 대리자에서 구성 요소 대리자를 제거할 수 있습니다.

예제

using System;

// Define a custom delegate that has a string parameter and returns void.
delegate void CustomDel(string s);

class TestClass
{
    // Define two methods that have the same signature as CustomDel.
    static void Hello(string s)
    {
        System.Console.WriteLine("  Hello, {0}!", s);
    }

    static void Goodbye(string s)
    {
        System.Console.WriteLine("  Goodbye, {0}!", s);
    }

    static void Main()
    {
        // Declare instances of the custom delegate.
        CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;

        // In this example, you can omit the custom delegate if you 
        // want to and use Action<string> instead.
        //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel;

        // Create the delegate object hiDel that references the
        // method Hello.
        hiDel = Hello;

        // Create the delegate object byeDel that references the
        // method Goodbye.
        byeDel = Goodbye;

        // The two delegates, hiDel and byeDel, are combined to 
        // form multiDel. 
        multiDel = hiDel + byeDel;

        // Remove hiDel from the multicast delegate, leaving byeDel,
        // which calls only the method Goodbye.
        multiMinusHiDel = multiDel - hiDel;

        Console.WriteLine("Invoking delegate hiDel:");
        hiDel("A");
        Console.WriteLine("Invoking delegate byeDel:");
        byeDel("B");
        Console.WriteLine("Invoking delegate multiDel:");
        multiDel("C");
        Console.WriteLine("Invoking delegate multiMinusHiDel:");
        multiMinusHiDel("D");
    }
}
/* Output:
Invoking delegate hiDel:
  Hello, A!
Invoking delegate byeDel:
  Goodbye, B!
Invoking delegate multiDel:
  Hello, C!
  Goodbye, C!
Invoking delegate multiMinusHiDel:
  Goodbye, D!
*/

참고 항목

참조

이벤트(C# 프로그래밍 가이드)

MulticastDelegate

개념

C# 프로그래밍 가이드

변경 기록

날짜

변경 내용

이유

2010년 9월

설명과 예제 코드가 이해하기 쉽도록 수정되었습니다.

고객 의견