【问题标题】:overriding virtual event压倒一切的虚拟事件
【发布时间】:2013-01-03 19:58:35
【问题描述】:

我有以下代码

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;
}

为什么我订阅了ScannerBurroughs实例的onFinalLeitura事件,却坚持执行基类(ScannerGCPerif)的事件声明,异常在哪里?

【问题讨论】:

    标签: events inheritance virtual


    【解决方案1】:

    我运行了您的代码,但没有出现异常。让我解释一下会发生什么:

    您在具体类中覆盖事件,但您没有提供添加和删除事件处理程序的实现,因此编译器生成以下代码:

    public class ScannerBurroughs : ScannerGCPerif
    {
        private NotificacaoScanner _onFinalLeitura; // Declare a private delegate
    
        public override event NotificacaoScanner onFinalLeitura
        {
            add { _onFinalLeitura += value; }
            remove { _onFinalLeitura -= value; }
        }
    }
    

    在幕后,它添加了一个私有委托并自动实现添加/删除事件访问器。订阅时永远不会调用基本实现。尝试显式实现访问器,在代码中放置一些断点,看看会发生什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多