개발 이야기/c#

델리게이트(delegate) 대리자 ?

요령도사 2018. 1. 5. 16:32
반응형

delegate를 활용하여 코드를 단순화 시켜보자

함수마다 반복되는 처리가 있고 특정 함수를 호출할때 RequestProc() 함수를 활용할 수 있다.

제네릭한 delegate인 Func / Action / Predicate 도 알아두자

@ 차이

Func 리터값 있음

Action 리턴값 없음

Predicate 리턴값 bool, 입력값 T


delegate string MyDelegate(string param);


static void Main(string[] args)

{

    MyCall myCall = new MyCall();

    MyClass test = new MyClass();


    // Call MyFunc1

    Console.WriteLine(test.RequestProc(myCall.MyFunc1, "test"));


    // Call MyFunc2

    Console.WriteLine(test.RequestProc(myCall.MyFunc2, "test"));

}


class MyClass

{

    public string RequestProc(MyDelegate myDelegate, string param)

    {

        return myDelegate(param);

    }

}


class MyCall

{

    public string MyFunc1(string param)

    {

        return param + " : MyFunc1";

    }


    public string MyFunc2(string param)

    {

        return param + " : MyFunc2";

    }

}


반응형