2013-07-15 17 views
0

該構造函數我似乎在C#與構造,繼承和事件訂閱的問題。訂閱繼承方法的事件在構造函數中,然後調用繼承

考慮下面的C#程序:要顯示

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace EventTest 
{ 
    public class Widget 
    { 
     public delegate void MyEvent(); 
     public event MyEvent myEvent; 

     public void SetEvent() 
     { 
      myEvent(); 
     } 
    } 

    public class Base 
    { 
     Widget myWidget; 

     protected Base() { } 

     protected Base(Widget awidget) 
     { 
      myWidget = awidget; 
      myWidget.myEvent += myEvent; 
     } 

     public void myEvent() { } 
    } 

    public class Derived : Base 
    { 
     public Derived(Widget awidget) : base(awidget) { } 

     new public void myEvent() 
     { 
      System.Console.WriteLine("The event was fired, and this text is the response!"); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Widget myWidget = new Widget(); 
      Derived myDerived = new Derived(myWidget); 

      myWidget.SetEvent(); 
     } 
    } 

} 

我想是的文本。即我想爲繼承的基類方法訂閱基類中的事件,然後能夠在子類中調用構造函數,並在觸發該事件時獲取子類的「事件方法,而不是基類」。

有沒有辦法做到這一點?

回答

1

您需要設置方法虛擬:

public class Base 
{...  

    public virtual void myEvent() { } 

,並覆蓋其

public class Derived : Base 
{ 
    ... 

    public override void myEvent() 
    { 
     System.Console.WriteLine("The event was fired, and this text is the response!"); 
    } 
} 
0
new public void myEvent() 

這會創建一個新的事件。你不想那樣。使該事件virtual在基類中,並使用override代替new這裏。

0

馬克基類方法,如虛擬和您的問題將得到解決。

public virtual void myEvent() { }