Two minutes event-handling code to understand how to write the C #

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Many online presentation C # event handling mechanism of the article, but many are too complex, vague concept, far-fetched analogy, more and more do not understand ......
In fact, what is so complicated.

Consider the following code, read direct message call me, I will not also the mouth ~!

public class Program
    {
        delegate void EventFunType(int x);//先定义一个事件处理程序的代理类型
       
        class EventTester //这个是会发生这个事件的对象
        {
            public event EventFunType onEvent;//这个就是他的事件处理方法储存器,目前是空的

            public void TestEvent()
            {
                onEvent?.Invoke(1);//这里是他触发事件的地方
            }
        }
       
        static void Main(string[] args)
        {
            Console.WriteLine("hello");

            EventTester tester = new EventTester();//建立对象                       
            tester.onEvent += new EventFunType(PlusOne);//添加一个处理方法
            tester.onEvent += new EventFunType(PlusTwo);//再添加一个处理方法
            tester.TestEvent();//触发

            Console.ReadKey();

            void PlusOne(int x)//这是事件的处理代码
            {
                Console.WriteLine("{0} + 1 = {1}", x, x + 1);
            }

            void PlusTwo(int x)//这是另一个事件的处理代码
            {
                Console.WriteLine("{0} + 1 = {1}", x, x + 2);
            }
        }
    }

Guess you like

Origin blog.csdn.net/foomow/article/details/91899388