|
web
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Pulling data objects from a collection of various data types storedI have a class which inherits 'Collection' and I use this class to store different data types. I'd like to have a method inside the class that does the following: For Each obj As Object In new_linked_collection Me.DoSomething(obj) Next where DoSomething is overloaded for each of the different data types I'm storing in the collection. The problem is, as I've defined obj as an Object, visual basic craps a brick unless I recast obj to a particlar type, such as For Each obj As Object In new_linked_collection If (obj.GetType.ToString.Equals("MyProgram.MyDataType1")) Then Dim castedObj As MyDataType1 = obj Me.DoSomething(castedObj) Else Dim castedObj As MyDataType2 = obj Me.DoSomething(castedObj) End If Next There has to be a more elegate way of doing this (expecially as I have more than 2 different data types stored in the collection). Any suggestions? Thanks a bunch, Kevin In article <1161781409.449590.120***@i3g2000cwc.googlegroups.com>,
kevinwo***@gmail.com says... Show quoteHide quote > Hello all, One idea is to use interfaces. Create an interface with a method called > > I have a class which inherits 'Collection' and I use this class to > store different data types. I'd like to have a method inside the class > that does the following: > > For Each obj As Object In new_linked_collection > Me.DoSomething(obj) > Next > > where DoSomething is overloaded for each of the different data types > I'm storing in the collection. The problem is, as I've defined obj as > an Object, visual basic craps a brick unless I recast obj to a > particlar type, such as > > For Each obj As Object In new_linked_collection > If (obj.GetType.ToString.Equals("MyProgram.MyDataType1")) > Then > Dim castedObj As MyDataType1 = obj > Me.DoSomething(castedObj) > Else > Dim castedObj As MyDataType2 = obj > Me.DoSomething(castedObj) > End If > Next > > There has to be a more elegate way of doing this (expecially as I have > more than 2 different data types stored in the collection). Any > suggestions? DoSomething: Public Interface IWorker Sub DoSomething() End Interface Have each of the "types" of objects you're storing in the collection implement the interface. Then just: for each obj as IWork in new_linked_collection obj.DoSomething() next Another idea is to change the type of parameter DoSomething receives to be an object and then use TypeOf to see what type is passed in: public sub DoSomething(o as object) if typeof(o) is MyDataType1 dim dt1 As MyDataType1 = DirectCast(o, MyDataType1) ' use dt1 end if if typeof(o) is MyDataType2 dim dt2 As MyDataType2 = DirectCast(o, MyDataType2) ' use dt2 end if end if |
|||||||||||||||||||||||