日期:2014-05-17 浏览次数:20816 次
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; }
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; }
------解决方案--------------------
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出来?