日期:2014-05-19  浏览次数:21046 次

C# 循环触发自定义事件的异常
在类中自定义事件.
并在类的方法中根据实际需要循环触发该事件.
用debug跟踪   ,结果发现:
循环触发的事件的次数=(2+循环次数)   *   循环次数   /2
即循环时,第一次触发1次
                      二             2
                        .             .
                        .             .
                        .             .
                        n             n

不知道如何解决该问题.何向各个大侠求救.
代码如下
自定义类
        class   Class1
        {
                public   Class1()
                {
                }
                public   delegate   void   test(int   index,int   count);
                public   event   test   testEvent;
                public   void   Client()
                {
                        //循环触发事件,测试用
                        for   (int   i   =   0;   i   <=   10;   i++)
                        {
                                testEvent(i+1,10);
                        }
                }
        }
-------------------------------------
调用该类的窗体
        public   partial   class   Form1   :   Form
        {
                private   Class1   cls;
                public   Form1()
                {
                        InitializeComponent();
                        cls   =   new   Class1();
                        cls.testEvent   +=   new   Class1.test(cls_testEvent);
                }

                void   cls_testEvent(int   index,   int   count)
                {
                        Trace.Listeners.Add(new   TextWriterTraceListener(Console.Out));