简体   繁体   中英

Function overloads based on interface inheritance

Say I have a base interface, and another one inheriting from it :

Public Interface Parent
    {stuff}
End Interface

And

Public Interface Child
    Inherits Parent
    {other stuff}
End Interface

I also have a sub and its overload :

Public Sub doStuff(parameter As Parent)
     {do some stuff}
End Sub 

And

Public Sub doStuff(parameter As Child)
     {do some other stuff}
End Sub 

If I call the sub like this it calls the "child function" :

Dim myParam As Child = New SomeClassImplementingChild
doStuff(myParam)

However, is there any way to make it call the "child function" with something like this, assuming I don't know at compile time the type of the coolParameter :

Public Sub coolFunction(coolParameter As Parent)
    doStuff(coolParameter)
End Sub 

Dim myParam As Child = New SomeClassImplementingChild
coolFunction(myParam)

I have found a workaround which is I guess the closest I'll ever get to a solution:

doStuff(Convert.ChangeType(coolParameter, coolParameter.GetType))

That will convert to the "real" type at Runtime, effectively calling the right function. However, the functions all have to be public to be called that way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM