不调用阴影方法

时间:2010-12-30 00:12:11

标签: vb.net inheritance shadowing

我有一个类,我意识到它不会总是正确实例化,作为一个快速修复,我想我将它子类化并隐藏一些方法,以便程序可以继续运行而不会爆炸。当我运行该软件时,对方法的调用将解析为基础的实现,而不是子类。我正在使用VB.NET和.NET 2.0。这是我正在尝试做的一个例子:

Public Class SuperClass

  Public Sub New ()
    Dim type As Type = GetType(SubClass)
    If (Me.GetType() is type) Then
      //nothing
    Else
      //build real object
    EndIf
  End Sub

  Private Shared _Instance As SuperClass
  Public Shared ReadOnly Property Instance() As SuperClass
    Get
      If (_Instance Is Nothing) Then
        Try
          _Instance = New SuperClass()
        Catch ex As Exception
          Dim result As DialogResult = MessageBox.Show(text, caption, MessageBoxButtons.RetryCancel, MessageBoxIcon.Information)
          If (result = DialogResult.Retry) Then
            _Instance = New SuperClass()
            //this will probably cause problems of its own, but i'll cross that bridge later...
          Else
            _Instance = New SubClass()
          End If
        End Try

      End If
      Return _Instance
    End Get
  End Property

  Public Overridable Function MyFunction() As Integer
     Dim somethingReasonable As Integer //do something for real
     Return somethingReasonable
  End Function

End Class

Public Class SubClass
  Inherits SuperClass

  Public Sub New()
    //doesn't do what cause the exception in the first place
  End Sub

  Public Shadows Function MyFunction() As Integer
    //Do something safe
    Return -1
  End Function    

End Class

我不确定为什么在运行时调用基类。当我在调试器中检查对象时,它显然是SubClass类型,但是调用了SuperClass方法。访问对象是通过Instance Property。

我确定我做错了什么或做了一些错误的假设,但我无法弄清楚是什么。

谢谢, 布赖恩

1 个答案:

答案 0 :(得分:3)

如果方法被遮蔽而不是重写,则当实例是子类类型时,不会调用阴影方法 - 将调用的方法是基于接收器的编译时类型而不是运行时确定的时间类型。这是阴影和覆盖之间的根本区别。