시작하기

Delegate, Action 과 Func, 람다식, Event 통합 정리 1판. 

 

Delegate

대리자(Delegate)는 일종의 함수 포인트이다. 

내부적으로 Count  만큼 List 를 순회하는 연결리스트 구조를 형성 중

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
 
public class SamplesDelegate  {
   // Declares a delegate for a method that takes in an int and returns a String.
   public delegate String myMethodDelegate( int myInt );
 
   // Defines some methods to which the delegate can point.
   public class mySampleClass  
    {
 
      // Defines an instance method.
      public String myStringMethod ( int myInt )  {
         if ( myInt > 0 )
            return"positive" );
         if ( myInt < 0 )
            return"negative" );
         return ( "zero" );
      }
 
      // Defines a static method.
      public static String mySignMethod ( int myInt )  {
         if ( myInt > 0 )
            return"+" );
         if ( myInt < 0 )
            return"-" );
         return ( "" );
      }
   }
 
   public static void Main()  {
 
      // Creates one delegate for each method. For the instance method, an
      // instance (mySC) must be supplied. For the static method, use the
      // class name.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );
 
      // Invokes the delegates.
      Console.WriteLine"{0} is {1}; use the sign \"{2}\"."5, myD1( 5 ), myD2( 5 ) );
      Console.WriteLine"{0} is {1}; use the sign \"{2}\"."-3, myD1( -3 ), myD2( -3 ) );
      Console.WriteLine"{0} is {1}; use the sign \"{2}\"."0, myD1( 0 ), myD2( 0 ) );
   }
 
}
 
 
/*
This code produces the following output:
 
5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
cs

Action과  Func

 Action 은 매개 변수가 없고 값을 반환 하지 않는 함수를 캡슐화 하는 대리자이다.

어떤 반환 값을 원하지 않고 일련의 작업을 수행하고자 할때 유용하다.

자매품으로 Action<T>, Action<T1, T2> ....... 가 있다. 자세한 내용은 위 링크를 참고하자.

1
public delegate void Action();
cs
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
32
33
34
public class Name
{
   private string instanceName;
   
   public Name(string name)
   {
      this.instanceName = name;
   }
 
   public void DisplayToConsole()
   {
      Console.WriteLine(this.instanceName);
   }
 
   public void DisplayToWindow()
   {
      MessageBox.Show(this.instanceName);
   }
}
 
public class testTestDelegate
{
   public static void Main()
   {
      Name testName = new Name("Koani");
      //Action 명시적으로 새 대리자를 생성한 후 명명된 메서드를 할당
      Action showMethod = testName.DisplayToWindow;
      //무명 메서드로 할당
      Action showMethod = delegate() { testName.DisplayToWindow();};
      //람다식
      Action showMethod = () => testName.DisplayToWindow();
      showMethod();
   }
}
cs

 

Func<TResult>는 매개 변수가 없고 TResult 매개 변수에 지정된 형식의 값을 반환하는 메서드를 캡슐화 한다.

Action과 마찬가지로 자매품으로 Func<T, TResult>Func<T, T1, TResult>......  이 있다.

1
public delegate TResult Func<out TResult>();
cs

 

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
32
33
34
35
36
37
38
39
40
using System;
using System.IO;
 
public class TestDelegate
{
   public static void Main()
   {
      OutputTarget output = new OutputTarget();
      //명시적으로 새 대리자를 정의하고 명명된 메서드를 할당 하는 대신 대리자
      Func<bool> methodCall = output.SendToFile;
      //무명 메서드를 위임
      Func<bool> methodCall = delegate() { return output.SendToFile(); };
      //람다식
      Func<bool> methodCall = () => output.SendToFile();      
 
      if (methodCall())
         Console.WriteLine("Success!"); 
      else
         Console.WriteLine("File write operation failed.");
   }
}
 
public class OutputTarget
{
   public bool SendToFile()
   {
      try
      {
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         sw.Close();
         return true;
      }  
      catch
      {
         return false;
      }
   }
}
cs

 

람다식

람다식은 대리자 또는 식 트리 형식을 만드는 데 사용할 수 있는 익명함수 이다.

1
2
3
4
5
6
7
//대리자 
delegate int del(int i);  
static void Main(string[] args)  
{  
    del myDelegate = x => x * x;  
    int j = myDelegate(5); //j = 25  
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
//식 트리 
using System.Linq.Expressions;  
 
namespace ConsoleApplication1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Expression<del> myET = x => x * x;  
        }  
    }  
}
cs

 

식 람다

=> 연산자의 오른쪽에 식이 있는 람다식을 식 람다 라고 한다. 

1
2
3
4
5
6
7
8
9
10
//식 람다의 기본형식
(input-parameters) => expression
 
//둘 이상의 매개 변수는 괄호로 묶고 쉼표로 구분한다.
(x, y) => x == y
//컴파일러에서 입력 형식을 구분할 수 없을 경우도 있으니 이렇게 명시할 수 있다.
(int x, string s) => s.Length > x
 
//입력 매개 변수가 없을 경우
() => SomeMethod()
cs

 

문 람다

문 람다는 다음과 같이 중괄호 안에 문을 지정한다는 점을 제외하면 식 람다와 비슷하다.

1
(input-parameters) => { statement; }
cs
1
2
3
4
5
//문 람다의 본문에 지정할 수 있는 문의 개수에는 제한이 없지만 일반적으로 2-3개 정도만 지정한다.
delegate void TestDelegate(string s);
 
TestDelegate del = n => { string s = n + " World"
                          Console.WriteLine(s); };
cs

 

무명 메서드와 마찬가지로 문 람다는 식 트리를 만드는데 사용할 수 없다.

 

비동기 람다

Async 및 Await 키워드를 사용하여 비동기 처리를 통합하는 람다식과 문을 만든다.

 

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
public partial class Form1 : Form  
{  
    public Form1()  
    {  
        InitializeComponent();  
    }  
 
    private async void button1_Click(object sender, EventArgs e)  
    {  
        // ExampleMethodAsync returns a Task.
        //이 아래 부분을 람다식을 적용한다면  
        await ExampleMethodAsync();
        textBox1.Text += "\r\nControl returned to Click event handler.\n";  
        //이렇게 된다.
        button1.Click += async (sender, e) =>  
        {  
            // ExampleMethodAsync returns a Task.  
            await ExampleMethodAsync();  
            textBox1.Text += "\nControl returned to Click event handler.\n";  
        };    
    }  
 
    async Task ExampleMethodAsync()  
    {  
        // The following line simulates a task-returning asynchronous process.  
        await Task.Delay(1000);  
    }  
}
cs

 

Event

Event 키워드는 게시자 클래스에서 이벤트를 선언하는데 사용.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SampleEventArgs
{
    public SampleEventArgs(string s) { Text = s; }
    public String Text { get; } // readonly
}
public class Publisher
{
    // Declare the delegate (if using non-generic pattern).
    public delegate void SampleEventHandler(object sender, SampleEventArgs e);
 
    // Declare the event.
    public event SampleEventHandler SampleEvent;
 
    // Wrap the event in a protected virtual method
    // to enable derived classes to raise the event.
    protected virtual void RaiseSampleEvent()
    {
        // Raise the event by using the () operator.
        if (SampleEvent != null)
            SampleEvent(thisnew SampleEventArgs("Hello"));
    }
}
cs

 

 

 

 

 

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기