1. 델리게이트(Delegate)
- 메소드가 처리해야 할 것을 델리게이트에 위임 한다.
- 델리게이트만 호출을 하게 되면 델리게이트가 위임 받은 메소드들이 실행된다.
- 델리게이트는 위임을 받을 메소드의 파라미터, 리턴 값의 시그니처만을 정의한다.
그러므로 공용모듈을 설계할 때 특정 메소드가 아닌 비슷한 기능을 하는 다양한 메소드 실행이 가능하다.
- 델리게이트는 이벤트와 함께 많이 사용된다.
using System;
namespace TestPro
{
class Program
{
// delegate
delegate int Calculate(int num1, int num2);
private static int Add(int num1, int num2)
{
return num1 + num2;
}
private static int Subtract(int num1, int num2)
{
return num1 - num2;
}
static void Main(string[] args)
{
Calculate add = new Calculate(Add);
Calculate sub = new Calculate(Subtract);
Console.WriteLine("Calculate(Add) 1+2 : {0}", add(1, 2));
Console.WriteLine("Calculate(Sub) 1-2 : {0}", sub(1, 2));
}
}
}
2. 무명 메소드(Anonymous Method)
- 익명 메소드를 사용하면 명시적 선언 없이 필요한 시점 즉시 구문 작성을 가능하게 해준다.
using System;
namespace TestPro
{
class Program
{
// delegate
delegate int Calculate(int num1, int num2);
static void Main(string[] args)
{
// Anonymous Method
Calculate add = new Calculate(delegate(int num1, int num2) { return num1 + num2; });
Console.WriteLine("Calculate(Add) 1+2 : {0}", add(1, 2));
// lamba
Calculate sub = new Calculate((num1, num2) => num1 - num2 );
Console.WriteLine("Calculate(Sum) 1-2 : {0}", sub(1, 2));
}
}
}
3. 이벤트(Event)
- 이벤트는 어떠한 처리가 즉시 발생하는 것이 아니라 사용자의 행동이나 다른 모듈에서의 처리 완료 시점을
알 수 없을 때 유용한 패턴을 제공한다.
using System;
using System.IO;
namespace TestPro
{
public class EventTest
{
FileSystemWatcher watcher = new FileSystemWatcher();
public void Run()
{
// 실행되는 현재 폴더 설정
watcher.Path = Environment.CurrentDirectory;
Console.WriteLine(Environment.CurrentDirectory);
// 변경 내역을 조사할 형식 설정
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// 감시를 할 파일 확장자 설정
watcher.Filter = "*.txt";
// 이벤트 등록
watcher.Changed += new FileSystemEventHandler(wathcer_Changed);
watcher.Created += new FileSystemEventHandler(wathcer_Changed);
watcher.Deleted += new FileSystemEventHandler(wathcer_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
// 감시 시작
watcher.EnableRaisingEvents = true;
}
void watcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("old {0}{2}, new : {1}", e.OldName, e.Name, Environment.NewLine);
}
void wathcer_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Type : {0}{3} FullPath : {1}", e.ChangeType, e.FullPath, Environment.NewLine);
}
}
class Program
{
// delegate
delegate int Calculate(int num1, int num2);
static void Main(string[] args)
{
EventTest evTest = new EventTest();
evTest.Run();
Console.WriteLine(@"Press q to quit the sample");
while (Console.Read() != 'q') ;
}
}
}
'Language > C#' 카테고리의 다른 글
[C#] Func / Action / 익명 형식 (0) | 2020.12.26 |
---|---|
[C#] 확장 메소드(Extension Method) (0) | 2020.12.26 |
[C#] ref / out / params (0) | 2020.12.26 |
[C#] 프로퍼티(Property) / 인덱서(Indexer) (0) | 2020.12.26 |
[C#] 클래스 (0) | 2020.12.26 |