0

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

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 方法被调用。通过实例属性访问对象。

我确定我做错了什么或做出了一些错误的假设,但我不知道是什么。

谢谢,布赖恩

4

1 回答 1

3

如果一个方法被遮蔽而不是被覆盖,当实例是子类类型时,遮蔽方法将不会被调用——将被调用的方法取决于接收者的编译时类型而不是运行时类型. 这是阴影和覆盖之间的根本区别。

于 2010-12-30T00:16:36.783 回答