๐Ÿ“š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