Event Mechanism in C#

來源:互聯網
上載者:User
1.what is Event in C#
       simplely speaking,Event  in C# is that as one instance does one behaviour, it will receive the message and then react with the message.

2.Event Happening&Re-acting Mechanism

3.how to declare a Event
    i.first declare a delegte
    ii.secondly declare repective Event
    like the following codes:
        public delegate void MyNewEvent(|object sender|,|MyEventArgs e|);
        public event MyNewEvent OnMyNewEvent;

4.Event Demo project
    E.g. Cat& Mouse problem.
            A mouse wanna steal something, at the same time, A cat is tracking him. Once the mouse is stealing , it will touch something and make noise. and then, the cat will know the mouse is stealing and receive the message and re-act at once. please create a project to realiaze this schema.
            the codes are following:

namespace CatMouse
{

    public class mouse
    {
       public delegate void MouseSteel(string food);
        public event MouseSteel OnMouseSteel;  //declare an Event     

    public void MouseIsSteeling(string food)
        {
            Console.WriteLine("Sender side: I am a mouse , I am steeling {0}\n", food);
            if (OnMouseSteel != null)
                //if there exists a listener who is listen to this event,  OnMouseSteel object will not be null; else it will be null;
                OnMouseSteel(food);
        }
      
    }

    public class cat
    {
        public cat(mouse tmp_mouse)
        {
            this.A_mouse = tmp_mouse;
            A_mouse.OnMouseSteel += new mouse.MouseSteel(A_mouse_OnMouseSteel);
            // once the mouse is stealing, the cat will re-act by  method <A_mouse_OnMouseSteel>
        }

        void A_mouse_OnMouseSteel(string food)
        {
            Console.WriteLine("Receiver side: Cat ! A mouse is steeling {0}\n", food);
          
        }
        private mouse A_mouse;

    }
    class Program
    {
        static void Main(string[] args)
        {
            mouse A_mouse=new mouse();
            cat A_cat = new cat(A_mouse);
            A_mouse.MouseIsSteeling("bread");
            A_mouse.MouseIsSteeling("fish");
            A_mouse.MouseIsSteeling("milk");
            A_mouse.MouseIsSteeling("butter");
            Console.Read();
        }
    }
}

        and if everything works well, we will such window:

congratulations!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.