Reputation: 415
is it possible to extend different classes with the same generic class? I tried something like this:
Public Class A
Public Sub TestA()
Debug.Print("Test A")
End Sub
End Class
Public Class B(Of T)
Public Sub TestB()
Debug.Print("Test B")
End Sub
End Class
Public Class C
Inherits B(Of A)
Public Sub TestC()
TestA() '**<-- Thows error 'is not declared'**
TestB()
Debug.Print("Test C")
End Sub
End Class
I basicly have some usercontrols, which derive from Combobox or Textbox and i'd like both to implement some functions(and interfaces) that are defined in a base class. In C++ i'd do it with multi inheritance.
Upvotes: 2
Views: 609
Reputation: 415
Thanks to your hint i got this working with extentions
Public Class Form1
Public Interface IA
Property val As String
End Interface
Public Class A
Public Sub test()
Debug.Print("test")
End Sub
End Class
Public Class C
Inherits A
Implements IA
Public Property val As String Implements IA.val
Public Sub TestC()
val = "testxxx"
TestA()
test()
End Sub
End Class
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ct As New C
ct.TestC()
End Sub
End Class
Module TestModule
<Extension()>
Public Sub TestA(ByVal pvIA As IA)
Debug.Print(pvIA.val)
End Sub
End Module
This way every class can implement it's own 'parent' (like A here) and i don't need to implement the function TestA for every class.
thank you
Upvotes: 0
Reputation: 8763
You could make both your Combobox and your Textbox classes implement the same interface.
Then you could define extension methods on that interface class.
Upvotes: 2
Reputation: 1500485
is it possible to extend different classes with the same generic class?
Generics isn't some kind of "workaround" for a lack of multiple inheritance, no. Your class C
doesn't derive from A
- it just means that the T
in B(Of T)
would be A
in the context of C
.
Which instance of A
would you expect TestA()
to be called on? Creating an instance of C
certainly doesn't create an instance of A
...
The fact that B(Of T)
doesn't use T
anywhere should be a warning signal - types which are generic but never use their generic type parameters are generally problematic.
It's hard to know exactly how to help you solve your real problem without more details, but you can't add a common base class in like this, when you also need to derive from other types which aren't under your control.
Perhaps extension methods would help?
Upvotes: 4