Martin Bryant

I have several classes with identically named 'Shared' methods (n.b. Shared not instance)
e.g.
Class1.DoIt()
Class2.DoIt()
Class3.DoIt()

Then I have another class (say Class4) which takes a type (n.b. a type, not an instance) as a parameter in its constructor...
e.g.
Public Sub New(ByVal type As Type)
...which I might invoke like...
class4Instance = New Class4(GetType(Class1))

Now within Class4 I want to invoke the Shared 'DoIt' method of the class type passed in.
I can do this using...
type.InvokeMember("DoIt", Reflection.BindingFlags.InvokeMethod, Nothing, Nothing, Nothing)
...but this seems rather ugly.

It's like I really want polymorphic Shared methods but as far as I can tell you can't do that ! !
e.g. I could have a Class0 which has a DoIt signature, Classes 1 thru 3 inherit from Class0, then I could somehow cast 'type' to Class0 and have something like CType(type, Class0).DoIt() ... [but of course that can't be done!]

Is there an easier way that I'm missing




Re: Visual Basic Language Polymorphic Shared methods???

Adamus Turner

You can have 2 or more functions/procedures with the same name as long as the datatypes or number of parameters are different.

Shared MySub (test as string)

End Sub

Shared MySub(test as integer)

End Sub

Shared MySub(test as string, test2 as integer)

End Sub

Adamus






Re: Visual Basic Language Polymorphic Shared methods???

Martin Bryant

Indeed you can, but I really don't think that answers my question :-)



Re: Visual Basic Language Polymorphic Shared methods???

decyclone

Hey Martin,

I know the code that uses Reflection looks ugly, but that is the only way to do that (I haven't seen any).

What you are talking about is similar to Duck Typing, but your method is static (Shared). Here is a good example of implementing duck typing in .Net using runtime interface implementation. But I think it is only useful if the method is not Shared, because interfaces don't support Shared members.

Hope this helps.





Re: Visual Basic Language Polymorphic Shared methods???

Stephen Weatherford MS

How about passing in a function delegate to invoke instead of a raw type Otherwise it seems like you need to use a non-shared method and interfaces (or the reflection solution) for what you want to do. There are similar patterns in the .net framework (e.g. UITypeEditor).