반응형
이벤트는 어떠한 문제가 발생했다는 사실을 개체가 시스템의 모든 관련 구성 요소에 전달하는 방법입니다.
보통 클래스내에 발생하는 이벤트를 외부에 전달할 수 있습니다.
+= 연산자를 사용하여 이벤트를 추가할 수 있다.
-= 연산자를 사용하여 이벤트를 제거할 수 있다.
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.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Output
{
public event EventHandler print;
public void totalOutput()
{
if (this.print != null)
{
print(this, EventArgs.Empty);
}
}
}
class Program
{
static void Output1(object sender, EventArgs args)
{
Console.WriteLine("Output1");
}
static void Output2(object sender, EventArgs args)
{
Console.WriteLine("Output2");
}
static void Main(string[] args)
{
Output output = new Output();
output.print += new EventHandler(Output1);
output.print += new EventHandler(Output2);
output.totalOutput();
}
}
}
|
지금은 간단하게 함수를 이벤트에 추가하게되면 이벤트를 호출 시 추가한 함수들이 같이 순차적으로 호출되게 됩니다.
그리고 추가와 삭제를 클래스 객체의 get이나 set처럼 add와 remove를 사용하여 추가 삭제가 가능합니다.
다음과 같이 사용할 수 있습니다.
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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Output
{
private EventHandler _print;
public event EventHandler print
{
add
{
_print += value;
}
remove
{
_print -= value;
}
}
public void totalOutput()
{
if (this._print != null)
{
_print(this, EventArgs.Empty);
}
}
}
class Program
{
static void Output1(object sender, EventArgs args)
{
Console.WriteLine("Output1");
}
static void Output2(object sender, EventArgs args)
{
Console.WriteLine("Output2");
}
static void Main(string[] args)
{
Output output = new Output();
output.print += new EventHandler(Output1);
output.print += new EventHandler(Output2);
output.totalOutput();
}
}
}
|
이렇게 add와 remove를 사용할 수 있습니다.
private EventHandler _print;
public event EventHandler print
{
add
{
_print += value;
}
remove
{
_print -= value;
}
}
반응형
'개발공부 > C#' 카테고리의 다른 글
[C#] 이벤트(event) & 델리게이트(delegate) (0) | 2019.10.17 |
---|---|
[C#] delegate (0) | 2019.10.16 |
[C#] yield (0) | 2019.10.14 |
[C#] 반복문 (0) | 2019.10.13 |
[C#] 조건문 (0) | 2019.10.12 |