Raise an event of a class from a different class in C#

后端 未结 12 916
庸人自扰
庸人自扰 2020-11-28 07:44

I have a class, EventContainer.cs, which contains an event, say:

public event EventHandler AfterSearch;

I have another class, EventRaiser.c

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 08:12

    Very simple example. i like to do it this way using EventHandler.

        class Program
        {
            static void Main(string[] args)
            {
                MyExtension ext = new MyExtension();
                ext.MyEvent += ext_MyEvent;
                ext.Dosomething();
                Console.ReadLine();
            }
    
            static void ext_MyEvent(object sender, int num)
            {
                Console.WriteLine("Event fired.... "+num);
            }
        }
    
        public class MyExtension
        {
            public event EventHandler MyEvent;
    
            public void Dosomething()
            {
                int no = 1;
    
                if (MyEvent != null)
                    MyEvent(this, ++no);
            }
        }
    }
    

提交回复
热议问题