๐Event
Event ํน์ฑ
using System.Windows.Forms;
namespace MySystem
{
class MyArea : Form
{
public MyArea()
{
// ์ด ๋ถ๋ถ์ ๋น๋ถ๊ฐ ๋ฌด์. (๋ฌด๋ช
๋ฉ์๋ ์ฐธ์กฐ)
// ์์ ๋ฅผ ํ
์คํธํ๊ธฐ ์ํ ์ฉ๋์.
this.MouseClick += delegate { MyAreaClicked(); };
}
public delegate void ClickEvent(object sender);
// event ํ๋
// delegate๋ ๋ค๋ฅธ์ ์ event ํค์๋๊ฐ ๋ถ๊ณ
// ์ธ๋ถ์์ MyClick() ์ง์ ํธ์ถ ๋ชปํ๋ค๋๊ฒ.
public event ClickEvent MyClick;
// ์์ ๋ฅผ ๋จ์ํ ํ๊ธฐ ์ํด
// MyArea๊ฐ ํด๋ฆญ๋๋ฉด ์๋ ํจ์๊ฐ ํธ์ถ๋๋ค๊ณ ๊ฐ์
void MyAreaClicked()
{
if (MyClick != null)
{
MyClick(this);
}
}
}
class Program
{
static MyArea area;
static void Main(string[] args)
{
area = new MyArea();
// ์ด๋ฒคํธ ๊ฐ์
area.MyClick += Area_Click;
area.MyClick += AfterClick;
// ์ด๋ฒคํธ ํํด
area.MyClick -= Area_Click;
// Error: ์ด๋ฒคํธ ์ง์ ํธ์ถ ๋ถ๊ฐ
//area.MyClick(this);
area.ShowDialog();
}
static void Area_Click(object sender)
{
area.Text += " MyArea ํด๋ฆญ! ";
}
static void AfterClick(object sender)
{
area.Text += " AfterClick ํด๋ฆญ! ";
}
}
}
์ด ๋ถ๋ถ ์ฃผ๋ชฉ
// Error: ์ด๋ฒคํธ ์ง์ ํธ์ถ ๋ถ๊ฐ //area.MyClick(this);
์ฌ๋ฐ๋ฅธ ์ฌ์ฉ
namespace test
{
class Test1
{
public delegate void testDelegate(string str);
public event testDelegate tDelegate;
public void eventTest(string str)
{
if (tDelegate != null)
{
tDelegate(str);
}
}
}
class Program
{
static void Main(string[] args)
{
Test1 t1 = new Test1();
t1.tDelegate += aaa;
//t1.tDelegate("asdf"); //์ด๊ฑฐ ์๋จ.
t1.eventTest("1111");
t1.tDelegate += bbb;
t1.eventTest("2222");
t1.tDelegate -= aaa;
t1.eventTest("3333");
}
static void aaa(string str)
{
Console.WriteLine("aaa str: {0}", str);
}
static void bbb(string str)
{
Console.WriteLine("bbb str: {0}", str);
}
}
}
Last updated