[oop] 델리게이트 란 무엇입니까? [닫은]

대리인의 실제 역할이 무엇인지 혼동하고 있습니까?

면접에서이 질문을 여러 번 받았지만 면접관이 내 대답에 만족했다고 생각하지 않습니다.

누구나 실례를 통해 한 문장으로 최고의 정의를 말해 줄 수 있습니까?



답변

델리게이트를 “함수에 대한 포인터”라고 생각하고 싶습니다. 이것은 C 일로 거슬러 올라가지 만 아이디어는 여전히 유효합니다.

아이디어는 코드를 호출 할 수 있어야하지만 호출 할 코드는 런타임까지 알려지지 않는다는 것입니다. 따라서 해당 목적을 위해 “대리인”을 사용합니다. 대리인은 예를 들어 다른 이벤트를 기반으로 다른 작업을 수행하는 이벤트 처리기 등의 작업에 유용합니다.

여기 당신이 볼 수 C #을위한 참조 :

예를 들어 C #에서 계산을하고 런타임까지 알 수없는 다른 계산 방법을 사용하려고한다고 가정 해 보겠습니다. 따라서 다음과 같은 몇 가지 계산 방법이있을 수 있습니다.

public static double CalcTotalMethod1(double amt)
{
    return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
    return amt * .056 + 42.43;
}

다음과 같이 델리게이트 서명을 선언 할 수 있습니다.

public delegate double calcTotalDelegate(double amt);

그런 다음 대리자를 다음과 같은 매개 변수로 사용하는 메서드를 선언 할 수 있습니다.

public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
    return calcTotal(amt);
}

그리고 CalcMyTotal사용하려는 델리게이트 메소드를 전달 하는 메소드를 호출 할 수 있습니다.

double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);


답변

델리게이트는 단순히 함수 포인터입니다.
델리게이트를 실행할 방법을 지정하기 만하면됩니다. 나중에 코드에서 Invoke를 통해 해당 메소드를 호출 할 수 있습니다.

설명 할 코드 (구문이 꺼져있을 수 있도록 메모리에서 작성)

delegate void delMyDelegate(object o);

private void MethodToExecute1(object o)
{
    // do something with object
}

private void MethodToExecute2(object o)
{
    // do something else with object
}

private void DoSomethingToList(delMyDelegate methodToRun)
{
    foreach(object o in myList)
        methodToRun.Invoke(o);
}

public void ApplyMethodsToList()
{
    DoSomethingToList(MethodToExecute1);
    DoSomethingToList(MethodToExecute2);
}


답변

여기에서 찍은

Q 델리게이트 란 무엇입니까?
A 개체가 요청을 받으면 개체는 요청 자체를 처리하거나 작업을 수행하기 위해 두 번째 개체에 요청을 전달할 수 있습니다. 객체가 요청을 전달하기로 결정하면 객체가 요청을 처리하는 책임을 두 번째 객체로 전달했다고 말합니다.

또는 쉬운 의사 예제로 무언가가 object1에 요청을 보냅니다. 그런 다음 object1은 요청과 그 자체를 object2 (대리인)에게 전달합니다. object2는 요청을 처리하고 일부 작업을 수행합니다. (참고 : 위의 링크는 좋은 예입니다)


답변

위임은 명령 패턴의 단순화 된 구현에 대해 생각하십시오.


답변

델리게이트는 메소드를 참조 할 수있는 객체입니다. 따라서 델리게이트를 만들 때 메서드에 대한 참조를 보유 할 수있는 객체를 만듭니다. 또한이 참조를 통해 메소드를 호출 할 수 있습니다. 따라서 델리게이트는 자신이 참조하는 메소드를 호출 할 수 있습니다. 델리게이트의 주요 장점은 메소드 호출을 지정할 수 있지만 실제로 호출 된 메소드는 컴파일 타임이 아니라 런타임에 결정된다는 것입니다.

간단한 위임

Declaration of delegate:
delegate-modifier delegate return-type delegate-name(parameters)
Implementation of delegate:
Delegate-name delegate-object=new Delegate-name(method of class)

http://knowpacific.wordpress.com/2012/01/26/delegate/


답변

여기에서는 델리게이트, 멀티 캐스트 델리게이트 및 사용법을 설명하겠습니다. 델리게이트는 객체에서 메서드 참조를 보유하는 유형입니다. 타입 안전 함수 포인터라고도합니다. 델리게이트는 메소드 서명을 정의하는 유형이라고 말할 수 있습니다.

델리게이트를 인스턴스화 할 때 인스턴스와 호환되는 서명이있는 메소드를 연결할 수 있습니다. 델리게이트 인스턴스를 통해 메소드를 호출하거나 호출 할 수 있습니다. 대리인은 메서드를 다른 메서드에 인수로 전달하는 데 사용됩니다. 이벤트 핸들러는 델리게이트를 통해 호출되는 메소드에 지나지 않습니다. 델리게이트 사용의 장점은 호출자의 메소드 호출 캡슐화 델리게이트를 효과적으로 사용하면 응용 프로그램의 성능이 향상됩니다. 메소드를 비동기 적으로 호출하는 데 사용됩니다. 대리인의 일부 속성이 있습니다

Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.

공개 대리자 type_of_delegate delegate_name () // 선언

You can use delegates without parameters or with parameter list
If you are referring to the method with some data type then the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer. Here I am giving an example with String.

다음 예제는 델리게이트 작업을 보여줍니다.

    namespace MyDelegate
    {
        class Program
        {
            private delegate void Show(string s);


            // Create a method for a delegate.
            public static void MyDelegateMethod(string me

ssage)
        {
            System.Console.WriteLine(message);
        }

        static void Main(string[] args)
        {
            Show p = MyDelegateMethod;
            p("My Delegate");
            p.Invoke("My Delegate");
            System.Console.ReadLine();
        }
    }
}

멀티 캐스트 델리게이트 란 무엇입니까?

둘 이상의 메소드에 대한 참조를 보유하는 대리자입니다. 멀티 캐스트 대리자는 void를 반환하는 메서드 만 포함해야합니다. 그렇지 않으면 런타임 예외가 있습니다.

 delegate void MyMulticastDelegate(int i, string s);
 Class Class2
 {
  static void MyFirstDelegateMethod(int i, string s)
  {
    Console.WriteLine("My First Method");
  }

  static void MySecondDelegateMethod(int i, string s)
  {
    Console.WriteLine("My Second Method");
  }

  static void Main(string[] args)
  {
    MyMulticastDelegate Method= new MyMulticastDelegate(MyFirstDelegateMethod);
    Method+= new MyMulticastDelegate (MySecondDelegateMethod);
    Method(1,"Hi");             // Calling 2 Methodscalled
    Method-= new MyMulticastDelegate (MyFirstDelegateMethod);
    Method(2,"Hi");             //Only 2nd Method calling
  }
}

여기서 위임은 + = 연산자를 사용하여 추가되고-= 연산자를 사용하여 제거됩니다.

델리게이트 유형은 .NET Framework의 델리게이트 클래스에서 파생됩니다. 델리게이트 유형은 봉인되어 있으며 파생 될 수 없습니다. 인스턴스화 된 대리자는 개체이므로 매개 변수로 전달되거나 속성에 할당 될 수 있습니다. 이렇게하면 메서드가 대리자를 매개 변수로 수락하고 나중에 대리자를 호출 할 수 있습니다. 이것을 비동기 콜백이라고합니다.


답변

델리게이트 패턴에 대한 자세한 설명과 실제 구현은 Google 컬렉션 전달 클래스 (데코레이터 패턴)에서 확인할 수 있습니다.