日期:2014-05-17  浏览次数:20816 次

C# 继承类 的事件问题
C# code

        static void Main(string[] args)
        {
            B b = new B();
            b.OnTestEvent +=new TestHandler(delegate
                {
                    Console.WriteLine("执行了事件");   
                });
            new B().Test();
            Console.Read();
        }

        public class B : A
        {
            public void Test()
            {
                Demo();
                OnTestEvent();// 这里报错
            }
        }

        public class A : IA
        {
            public void Demo()
            {
                Console.WriteLine("Class A demo");              
            }
            public event TestHandler OnTestEvent;
        }

        public delegate void TestHandler();
        public interface IA
        {
            void Demo();
            event TestHandler OnTestEvent;
        }


我想要的是,A类继承接口IA,B类继承A类,
想在B类中某时刻触发事件OnTest(),然后向外通知。

------解决方案--------------------
C# code

      public class B : A
      {
          public void Test()
          {
              Demo();
              DoTest();
          }
      }

      public class A : IA
      {
          public void Demo()
          {
              Console.WriteLine("Class A demo");
          }
          protected void DoTest()
          {
              if (OnTestEvent != null)
              {
                  OnTestEvent();// 这里报错
              }
          }
          public event TestHandler OnTestEvent;
      }

------解决方案--------------------
C# code

    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            b.TestEvent += new TestHandler(delegate
            {
                Console.WriteLine("执行了事件");
            });
            //new B().Test();
            b.Test();
            Console.Read();
        }

        public class B : A
        {
            public void Test()
            {
                Demo();
                OnTestEvent();// 这里报错
            }
        }

        public class A : IA
        {
            public void Demo()
            {
                Console.WriteLine("Class A demo");
            }
            public event TestHandler TestEvent;

            protected virtual void OnTestEvent()
            {
                if (TestEvent != null)
                {
                    TestEvent();
                }
            }


        }

        public delegate void TestHandler();

        public interface IA
        {
            void Demo();
            event TestHandler TestEvent;
        }
        
    }

------解决方案--------------------
L1正解,我的想法也是一样的
------解决方案--------------------
正解 你干嘛再new一个B出来?
探讨
C# code

class Program
{
static void Main(string[] args)
{
B b = new B();
b.TestEvent += new TestHandler(delegate
{
……