티스토리 뷰

개발언어/C#

[C#] Action / Func 대리자

kr98gyeongim 2021. 3. 9. 17:37

오늘은 C#의 Action 대리자와 Func 대리자에 대해서 기록.

 

[참고]

- Action대리자는 반환값이 없다.

- Func 대리자는 반환값이 있다.

따라서, 반환값이 필요한 경우에는 Func 대리자를 사용하자!

 

[Action 대리자 형태]

・Action

・Action<in T1>

・Action<in T1...T16>

 

[Action 대리자 사용법 3가지]

・ 기존 메소드 지정

ex)

Action<string> testActionName1 = Print;

testActionName1("testActionName1메소드 호출");

public void Print(string msg)

{

      Console.WriteLine(msg);

}

 

・ 무명 메소드 지정

Action<string, string> testActionName2 = delegate(string errorId, string msg)

{

      Console.WriteLine(errorId, msg);

}

・ 람다식 사용

ex)

Action<string, int> testActionName3 = (x, y) =>

{

      Console.WriteLine(x, y);

      testActionName3("testActionName3 첫번째 인수 x값, 두번째 인수 y값은 ", 100 );

}

 

 

[Func 대리자 형태]

・Func<out TResult>

・Func<in T1, out TResult>

・Func<in T1, in T2, out TResult>

・Func<in T1, in T2, ...in T16, out TResult>

 

[Func 대리자 사용법 3가지]

・ 기존 메소드 지정

ex )

Func<string, string> testFuncName1 = Sum;

 

Console.WriteLine(testFuncName1(10, 25));

 

public int Sum(int x, int y)

{

      return x + y;

}

 

・ 무명 메소드 지정

ex)

Func<int, int, int> testFuncName2 = delegate(int x, int y)

{

      return x + y;

};

 

・ 람다식 사용

ex)

Func<int, string> testFuncName3 = (x, y, x) =>

{

      return "반환값 : " +( x + y + z ) ;

};.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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 31
글 보관함