블로그 이미지
따시쿵

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2015. 6. 9. 11:04 C#

 

2. Func와 Action으로 더 간편하게 무명 함수 만드는 경우

 

익명 메서드와 무명 함수는 코드를 더 간결하게 만들어주는 요소들입니다. 하지만 이들을 선언하기 전에 해야 하는 일들을 생긱해 보면 익명 메소드를 만들기위해서 매번 델리게이트를 선언합니다. 이 문제를 해결하기 위해 마이크로소프트는 Func와 Action 델리게이트를 미리 선언해 두었습니다.Func 델리게이트는 결과를 반환하는 메소드를 참조하기 위해, Action 델리게이트는 결과를 반환하지 않는 메소드를 참조합니다.

 

 

1. Func 델리게이트

 

.Net 프레임워크에서는 모두 17가지의 Func 델리게이트가 미리 준비되어 있습니다.

입력 파라미터는 최대 16개까지 사용 가능합니다.

 

 

Func<T, TResult> 델리게이트

 

 

구문

 

public delegate TResult Func<in T, out TResult>(
 T arg
)

 

형식 매개 변수

 

in T

 

     이 대리자로 캡슐화되는 메서드의 매개 변수 형식입니다.

     이 형식 매개 변수는 반공변입니다.

     즉, 지정한 형식이나 더 적게 파생되는 모든 형식을 사용할 수 있습니다.

 

out TResult

 

     이 대리자로 캡슐화되는 메서드의 반환 값 형식입니다.

     이 형식 매개 변수는 공변입니다.

     즉, 지정한 형식이나 더 많이 파생되는 모든 형식을 사용할 수 있습니다.

 

 

매개 변수

 

arg
      형식: T
      이 대리자로 캡슐화되는 메서드의 매개 변수입니다.

 

반환 값
     형식: TResult
     이 대리자로 캡슐화되는 메서드의 반환 값입니다.

 


설명

 

1. 이 대리자를 사용하면 사용자 지정 대리자를 명시적으로 선언하지 않고 매개 변수로 전달할 수 있는 메서드를 나타낼 수 있습니다.

 

2. 캡슐화된 메서드는 이 델리게이트에 의해 정의되는 메서드 시그니처(파라미터 타입과 갯수)와 일치해야 합니다. 즉, 캡슐화된 메서드에는 값으로 전달되는 매개 변수 하나가 있어야 하고 값을 반환해야 합니다.

 

 

예제1

 

ConvertMethod라는 델리게이트를 명시적으로 선언하고 UppercaseString 메서드에 대한 참조를 해당 델리게이트 인스턴스에 할당합니다.

    delegate string ConvertMethod(string inString);
    class Program
    {
        static void Main(string[] args)
        {
            ConvertMethod convertMeth = UppercaseString;
            string name = "Korea Forever !!!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convertMeth(name));

            Console.ReadLine();
        }

        static string  UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }
    }

 

에제2

 

다음 예제에서는 새 델리게이트를 명시적으로 정의하고 명명된 메서드를 할당하는 대신 Func<T, TResult> 델리게이트를 인스턴스화하여 이 코드를 간소화합니다.

        static void Main(string[] args)
        {
            Func<string, string> convertMethod = UppercaseString;
            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convertMethod(name));

            Console.ReadLine();
        }

        static string UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }

 

예제3

 

C#에서는 다음 예제와 같이 Func<T, TResult> 델리게이트를 anonymous method와 함께 사용할 수도 있습니다.

        static void Main(string[] args)
        {
            Func<string, string> convert = delegate(string s)
            {
                return s.ToUpper();
            };

            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convert(name));

            Console.ReadLine();
        }

 

예제4

 

다음 예제와 같이 Func<T, TResult> 델리게이트에 람다식을 할당할 수도 있습니다.

            Func<string, string> convert = (string s) => s.ToUpper();

            string name = "Korea Forever !!!";

            Console.WriteLine("Before convert string : {0}", name);
            Console.WriteLine("After convert string : {0}", convert(name));

            Console.ReadLine();

 

4개 예제에 대한 동일한 결과화면 입니다.

 

 

 

'C#' 카테고리의 다른 글

람다식(Lambda Expression) - 4  (0) 2015.06.11
람다식(Lambda Expression) - 3  (0) 2015.06.09
람다식(Lambda Expression) - 1  (0) 2015.06.08
EventHandler 와 EventHandler<TEventArgs> Delegate  (0) 2015.06.04
Event 와 Delegate  (0) 2015.06.01
posted by 따시쿵