我有以下代码
public delegate void NotificacaoScanner(NotifScanner e);
// interface
public interface IScanner
{
event NotificacaoScanner onFinalLeitura;
}
// abstract class that implements the interface
public abstract class ScannerGCPerif : IScanner
{
public virtual event NotificacaoScanner onFinalLeitura;
{
add { throw new NotImplementedException("Event not available for this service"); }
remove { throw new NotImplementedException("Event not available for this service"); }
}
}
// concrete class that implements the abstract class
public class ScannerBurroughs : ScannerGCPerif
{
public override event NotificacaoScanner onFinalLeitura;
}
为什么当我订阅onFinalLeitura
实例的ScannerBurroughs
事件时,它坚持执行基类的事件声明(ScannerGCPerif),其中有异常?
答案 0 :(得分:0)
我运行了你的代码而我没有得到异常。让我解释一下会发生什么:
您在具体类中覆盖事件,但是您没有提供添加和删除事件处理程序的实现,因此编译器会生成以下代码:
public class ScannerBurroughs : ScannerGCPerif
{
private NotificacaoScanner _onFinalLeitura; // Declare a private delegate
public override event NotificacaoScanner onFinalLeitura
{
add { _onFinalLeitura += value; }
remove { _onFinalLeitura -= value; }
}
}
在幕后,它添加了一个私人代理并自动实现了添加/删除事件访问器。订阅时永远不会调用基本实现。尝试显式实现访问器,在代码中放置一些断点,看看会发生什么。