|
-
May 11th, 2004, 06:20 AM
#1
Thread Starter
Frenzied Member
Proper inhertance?
In my project I have various classes... call them A, B, C etc...
For class A I needed the ability to store them in a collection... so I made this class (CDocument is A):
VB Code:
Public Class CDocumentCollection : Inherits CollectionBase
Public Sub Add(ByVal item As CDocument)
Me.List.Add(item)
End Sub
Public ReadOnly Property Item(ByVal index As Integer) As CDocument
Get
Return DirectCast(Me.List.Item(index), CDocument)
End Get
End Property
Public WriteOnly Property Item(ByVal index As Integer, ByVal Document As CDocument) As CDocument
Set(ByVal Value As CDocument)
Me.List.Item(index) = Document
End Set
End Property
End Class
Now let's say I need to do the same thing for B... Is the best way to do that is to create another class BCollection and define all the methods like I did above (add, item) but using the type B instead of type A(CDocument in the example code).
I feel like something stinks in my code here...
I feel like I should only need one collection class.. but since the objects to be stored in the collections have different parents... I can't do it with a base class as collection parameter...
Like if I had A-Z objecs.. all inherited from TheGod class.. then I could make a collection class like above using TheGod as parameter type... then all siblings should be accepted without any type conversions... polymorphism...
That is also the reason I made the class above in the first place.. I want it type safe! But is that possible to acieve WITHOUT for objects A-Z create ACollection-ZCollection?
kind regards
Henrik - pposting yet another bizarre OO question...
-
May 11th, 2004, 06:38 AM
#2
If you want different kinds of objects in one collection, then you will need to have some common super class, or interface. But that removes type safety. The only way you are going to get close to type safety and allow multiple classes to use the same collection class would probably be to simulate generics.
VB Code:
Imports System.Collections
Public Class CollectionClass : Inherits CollectionBase
Private _Type As Type
Public Sub New(ByVal T As Type)
_Type = T
End Sub
Public Sub Add(ByVal o As Object)
If o.GetType Is _Type Then
MyBase.List.Add(o)
Else
Throw New InvalidOperationException("Object is not of type " & _Type.Name)
End If
End Sub
End Class
Something like that.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|