Shadowed method is not called
I have a class which i realized will not always correctly instantiate and as a quick fix, i figured i'd subclass it and shadow a few methods so that the program can continue to run without exploding. When i run the software, calls to the methods resolve to the base's implementations and not the subclass. I'm using VB.NET with .NET 2.0. Here is an example of what i'm trying to do:
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
I'm not sure why the base class gets called during runtime. When i inspect the object in the debugger it is clearly the SubClass type but the SuperClass methods get called. Access to the object is through the Instance Property.
I'm sure i'm doing something wrong or making some wrong assumption but I can't figure out what.
Thanks, brian
If a method is shadowed rather than overridden, the shadowing methods will not be called when an instance is of subclass type -- the method which will be called is determined based on the compile-time type of the receiver rather than the run-time type. This is the fundamental difference between shadowing and overriding.
精彩评论