C#/기초
[c#] 자식 클래스의 이벤트를 부모 클래스 이벤트에 연결하기
떡잎
2020. 2. 1. 19:26
자식 클래스에서 발생한 이벤트를 부모 이벤트에 발생하게 하기 위한 간단한 소스
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
using System;
namespace EventTest
{
class Program
{
static void Main(string[] args)
{
Parent p = new Parent();
}
}
// 자식클래스 이벤트에서 사용할 델리게이트.
// 자식 클래스에서 이벤트가 발생할때 생성된 MyEventArgs 인스턴스가 부모 클래스에 전달된다.
public delegate void DelegateNotify(MyEventArgs customEventArgs);
// 부모 클래스
public class Parent
{
private Child mChild;
public Parent()
{
mChild = new Child();
// 자식 클래스 이벤트 등록
mChild.KeyPreesedEvent += new DelegateNotify(NotifyEvent);
mChild.ReadKey();
}
// 이벤트 리스너 : 자식 클래스에서 이벤트가 발생될 때, 호출된다.
void NotifyEvent(MyEventArgs myEventArgs)
{
Console.Write("\n" + myEventArgs.PressedTime);
Console.WriteLine(" [" + myEventArgs.Key + "] 키 눌림");
}
}
// 자식 클래스
public class Child
{
public Child() {}
// 부모 클래스에서 등록될 자식 클래스 이벤트
public event DelegateNotify KeyPreesedEvent;
public void ReadKey()
{
bool bContinue = true;
do
{
Console.Write("\n아무 키나 누르세요 : ");
ConsoleKeyInfo pressedKeyInfo = Console.ReadKey();
KeyPreesed(pressedKeyInfo.Key.ToString());
Console.WriteLine("계속 하나요? [Y=예]");
ConsoleKeyInfo keyInfo = System.Console.ReadKey();
if (keyInfo.Key == ConsoleKey.Y)
{
bContinue = true;
}
else
{
bContinue = false;
}
} while (bContinue);
}
public void KeyPreesed(string pressedKey)
{
if (KeyPreesedEvent != null)
{
MyEventArgs myEventArgs = new MyEventArgs(pressedKey);
// 이벤트 발생 : 이벤트 리스너를 호출
KeyPreesedEvent(myEventArgs);
}
}
}
public class MyEventArgs : EventArgs
{
private string mKey;
private string mPressedTime;
public MyEventArgs(string key)
{
mKey = key;
mPressedTime = DateTime.Now.ToString("yy-MM-dd HH:mm:ss");
}
public string Key
{
get { return mKey; }
set { mKey = value; }
}
public string PressedTime
{
get { return mPressedTime; }
set { mPressedTime = value; }
}
}
}
|
cs |