[C#] Func<T, TResult> Delegate (델리게이트 캡슐화)

|


델리게이트를 캡슐화 해서 명시적으로 델리게이트를 선언하지 않고도 이 제네릭을 이용하면 간편하게 사용이 가능하다. 

Func<T, TResult>는 내부적으로 델리게이트를 선언해서 사용하지만 사용자에게는 노출하지 않습니다.

따라서 사용자는 델리게이트를 몰라도 사용이 가능합니다.


T는 입력 파라미터, TResult는 결과 값이다.


1. 기존의 방법


01.delegate string ConvertMethod(string inString);
02.  
03.public class DelegateExample
04.{
05.   public static void Main()
06.   {
07.      // Instantiate delegate to reference UppercaseString method
08.      ConvertMethod convertMeth = UppercaseString;
09.      string name = "Dakota";
10.      // Use delegate instance to call UppercaseString method
11.      Console.WriteLine(convertMeth(name));
12.   }
13.  
14.   private static string UppercaseString(string inputString)
15.   {
16.      return inputString.ToUpper();
17.   }
18.}


2. Func(T,TResult) 대리자 사용시


01.public class GenericFunc
02.{
03.   public static void Main()
04.   {
05.      // Instantiate delegate to reference UppercaseString method
06.      Func<string, string> convertMethod = UppercaseString;
07.      string name = "Dakota";
08.      // Use delegate instance to call UppercaseString method
09.      Console.WriteLine(convertMethod(name));
10.   }
11.  
12.   private static string UppercaseString(string inputString)
13.   {
14.      return inputString.ToUpper();
15.   }
16.}


3. 할당은 무명메서드나 람다식을 이용도 가능하다.


01.public class Anonymous
02.{
03.   public static void Main()
04.   {
05.      Func<string, string> convert = delegate(string s)
06.         { return s.ToUpper();};
07.  
08.      string name = "Dakota";
09.      Console.WriteLine(convert(name));  
10.   }
11.}
12.  
13.  
14.public class LambdaExpression
15.{
16.   public static void Main()
17.   {
18.      Func<string, string> convert = s => s.ToUpper();
19.  
20.      string name = "Dakota";
21.      Console.WriteLine(convert(name));  
22.   }
23.}


And