Home > front end >  Using the Me object
Using the Me object

Time:07-15

MustInherit Class Person
    Overridable Function TableName() As String
        Return "Person"
    End Function
    Sub Save
        DoSomething(Me)
    End Sub
End Class

Class Staff
    Inherits Person
    Overrides Function TableName() As String
        Return "Staff"
    End Function
    Overloads Sub Save()
        MyBase.Save()
        DoSomething(Me)
    End Sub
End Class
Sub DoSomething(o as Object)
    DoAnotherThing(o.TableName)
End Sub

Is there a way I can get Me in DoSomething to refer to Person in Person.Save and Staff in Staff.Save? At the moment they both refer to the Staff instance.

I am trying to write a general routine to save properties to a database, the (inherited - not my code) problem is there are 3 objects inheriting Person (Staff, Clients, Contacts) and tons of almost-duplicated code, which makes 4 database tables (Person has data common to the 3).

CodePudding user response:

I wonder if this structure would help

MustInherit Class BasePersons
    'stuff common to classes that Inherit here
    MustOverride Function TableName() As String

    MustOverride Sub Save()

    Sub DoSomething(BP As BasePersons)
        'code
        Debug.WriteLine(BP.TableName)
    End Sub
End Class

Class Person
    Inherits BasePersons

    Overrides Function TableName() As String
        Return "Person"
    End Function

    Overrides Sub Save()
        DoSomething(Me)
    End Sub
End Class

Class Staff
    Inherits BasePersons

    Overrides Function TableName() As String
        Return "Staff"
    End Function

    Overrides Sub Save()
        DoSomething(Me)
    End Sub
End Class

CodePudding user response:

Since it only applies to one object, I just redefined a couple of subs

Sub DoSomething(o as Object, optional IsPerson as Boolean = false)
    Dim TableName As String = If(IsPerson, "Person", obj.TableName)        
    DoAnotherThing(o, TableName)
End Sub

Sub DoAnotherThing(o as Object, TableName as string)

Hacky, not at all OO, but good enough for me.

  • Related