[英]Subscribing inherited methods to events in a constructor, then calling that constructor in an inherited class
我在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();
}
}
}
我想要的是要顯示的文本。 即我想為基類中的事件訂閱繼承的基方法,然后能夠在子類中調用構造函數,並在觸發該事件時獲取要調用的子類的事件方法而不是基類。
有什么辦法嗎?
您需要將方法設置為virtual:
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!");
}
}
new public void myEvent()
這將創建一個新事件。 你不要那樣 使事件在基類中virtual
,並在此處使用override
而不是new
。
將基類方法標記為虛方法,您的問題將得到解決。
public virtual void myEvent() { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.