C# Action Delegate(C# Action 델리게이트, Lambda), 무명함수, 람다식
Action 델리게이트는 Func 델리게이트와 거의 유사하다. 차이점이라면 반환 형식이 없다는 것이다. 이 Action 델리리게이트 역시 닷넷4.0 프레임워크에는 대략 17가지 준비되어 있다.
public delegate TResult Action< >()
public delegate TResult Func<in T >(T arg)
public delegate TResult Func<int T1, in T2>(T1 arg, T2 arg)
public delegate TResult Func<int T1, in T2, in T3 >(T1 arg, T2 arg, T3 arg)
……
……
public delegate TResult Func<in T1,,,in T16>(T1 arg, T2 arg, T3 arg,,, T16 arg)
Func 델리게이트와는 반환값이 없는 것이 특징이며 형식 매개변수는 모두 입력 매개변수 이다.
[사용 예문]
입력 매개 변수가 없는 경우…
Action action1 = () => Console.WriteLine(“No Parameter Action Delegate”);
action1();
입력 매개 변수가 두개인 경우…
int sum=0;
//입력 매개변수는 둘, 더한 결과를 밖에서 선언한 sum에 저장
Action<int, int> action2 = (x, y) => sum=x*y;
action2(1,2);
Console.WriteLine(“1+2={0}”, sum); //9 리턴
[예제 1]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
//델리게이트 정의
delegate bool Onj1();
delegate bool Onj2(int i);
class Program
{
static void Main(string[] args)
{
Action act1 = () => Console.WriteLine("오라클자바커뮤니티프로그래밍");
act1();
int ret=0;
Action<int> act2 = (x) => ret = x * x;
act2(2);
Console.WriteLine("act2(2) :: {0}", ret);
Action<double, double> act3 = (x, y) =>
{
double d = x / y;
Console.WriteLine("Action<t1,t2>({0},{1}) : {2}", x, y, d);
};
act3(100, 3);
}
}
}
[결과]
오라클자바커뮤니티프로그래밍
act2(2) :: 4
Action<t1,t2>(100,3) : 33.3333333333333
[예제 2]
using System;
using System.Windows.Forms;
public delegate void ShowName();
public class Onj
{
private string name;
public Onj(string name)
{
this.name = name;
}
public void DisplayToConsole()
{
Console.WriteLine(this.name);
}
public void DisplayToWindow()
{
MessageBox.Show(this.name);
}
}
public class Program
{
public static void Main()
{
//delegate를 정의 후 호출
Onj onj1 = new Onj("실무개발자닷넷교육");
ShowName act1 = onj1.DisplayToWindow;
act1();
//Action delegate를 이용
Onj onj2 = new Onj("오라클자바커뮤니티");
Action act2 = onj2.DisplayToWindow;
act2();
//Action무명 메소드 이용
Onj onj3 = new Onj("오라클자바커뮤니티프로그래밍");
Action act3 = delegate()
{
onj3.DisplayToWindow();
};
act3();
//Action delegate에 람다식 이용
Onj onj4 = new Onj("onjprogramming");
Action act5 = () => onj4.DisplayToWindow();
act5();
}
}
![]() | ![]() ![]() | 12-27 | 2554 | |
![]() | ![]() ![]() | 12-11 | 1863 | |
53 | ![]() ![]() | 03-15 | 1674 | |
52 | ![]() ![]() | 01-31 | 1768 | |
51 | ![]() ![]() | 01-31 | 2543 | |
50 | ![]() ![]() | 01-31 | 1402 | |
49 | ![]() ![]() | 01-19 | 1710 | |
48 | ![]() ![]() | 01-11 | 1592 | |
47 | ![]() ![]() | 01-03 | 2109 | |
46 | ![]() ![]() | 12-27 | 2554 | |
45 | ![]() ![]() | 12-19 | 1820 | |
44 | ![]() ![]() | 12-14 | 1803 | |
43 | ![]() ![]() | 12-11 | 1863 | |
42 | ![]() ![]() | 12-09 | 1462 | |
41 | ![]() ![]() | 12-01 | 1689 | |
40 | ![]() ![]() | 12-01 | 1862 | |
39 | ![]() ![]() | 12-01 | 1338 |
댓글 없음:
댓글 쓰기