【问题标题】:Shadowed method is not called不调用阴影方法
【发布时间】:2023-03-03 03:57:01
【问题描述】:

我有一个类,我意识到它不会总是正确地实例化,作为一个快速修复,我想我会将它子类化并隐藏一些方法,以便程序可以继续运行而不会爆炸。当我运行软件时,对方法的调用会解析为基类的实现而不是子类。我正在使用带有 .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 方法被调用。通过实例属性访问对象。

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

谢谢, 布莱恩

【问题讨论】:

    标签: vb.net inheritance shadowing


    【解决方案1】:

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

    【讨论】:

    • 所以我应该将 sublcassed 方法声明为覆盖而不是阴影,并保持可覆盖的超类方法不变?
    • 是的,将子类方法声明为Overrides
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2019-10-27
    • 2013-06-30
    相关资源
    最近更新 更多