|
-
Sep 24th, 2003, 03:55 PM
#1
Thread Starter
Fanatic Member
Object Oriented Help With Collection
Hi all.
I have an object, say Beer. I have two sub classes that inherit from beer, LiteBeer and HeavyBeer.
I have a BeerCollection class that I want to use to hold collections of LiteBeer and HeavyBeer. This works fine, as the add method in the collection adds the item as Beer, but I can still access the child properties if cast it back.
The problem is this: I want the Item method in the collection to return the object as the specific type, not just as a Beer object (code below), so that the object is ready to be used.
VB Code:
Public ReadOnly Property Item(ByVal index As Integer) As Beer
I want something like:
VB Code:
Public ReadOnly Property Item(ByVal index As Integer) As Me.List.Item(0).GetType()
but obviously you can't do this. Is there any way to accomplish this with out making a separate collection for LiteBeer and HeavyBeer?
Thanks
-
Sep 24th, 2003, 04:22 PM
#2
Frenzied Member
Since the collection class is generic, it looks like you will have to cast.
-
Sep 24th, 2003, 04:31 PM
#3
I'd suggest you just make three different Item properties:
VB Code:
Public ReadOnly Property Item(ByVal index As Integer) As Beer
Public ReadOnly Property LiteItem(ByVal index As Integer) As LiteBeer
Public ReadOnly Property HeavyItem(ByVal index As Integer) As HeavyBeer
-
Sep 25th, 2003, 07:36 AM
#4
Thread Starter
Fanatic Member
My function to add only allows the same type of objects to be added. So my collection will only ever contain one type, not a mixture. So if I have 3 different item properties, then I guess I would throw an error when the other ones are used. For example, If my collection is of LiteBeer objects, then the HeavyItem property would throw an error?
Is that commonly done? Why make it available if it can't be used or just throws an error?
I guess this is better then making separate collections though. Hmmm.
-
Sep 25th, 2003, 09:47 AM
#5
No I don't think its commonly done. People would commonly use casting which is what you said you didn't want to have to do. And yes retieving a HeavyBeer with a LiteBeer index would give you an InvalidCast error.
-
Sep 25th, 2003, 09:55 AM
#6
Thread Starter
Fanatic Member
I think I will create a base collection Beer (abstract item method) and then create a LitBeer collection that inherits Beer collection. Then all I have to do is implement the Item property.
I think that is the best solution - the UI developer doesn't have to worry about casting.
-
Sep 25th, 2003, 10:09 AM
#7
Thread Starter
Fanatic Member
Thanks for your help, and if any other ideas come to mind, feel free to post!
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
|