Asp.net - Shared List Transfer

I have a utility class that takes a general list as a parameter.

The code looks like this:

Function DoStuff(collection as Object, elt as Object)
   ...
   collection.Add(elt)
   ...
End Function

Called with:

DoStuff( List(Of Foo), new Foo() )
DoStuff( List(Of Bar), new Bar() )

There are about a dozen different types.

Passing the Object currently leads to a late restriction warning, although it works fine.

I tried different methods of transferring to collections and elt (Foo and Bar extend the base class), but it seems they cannot determine the “correct” way to do this.

Ideas?

+3
source share
3 answers

I think you are looking for something like this.

Public Sub DoStuff(Of T)(collection As List(Of T), elt As T)
    ...
    collection.Add(elt)
    ...
End Function
+7
source

womp Qua, , , , 12 - ( ), , :

Public Sub DoStuff(Of T As YourBaseClass)(collection As List(Of T), elt As T)
    ...
    collection.Add(elt)
    ...
End Sub

, , YourBaseClass.

+3

/ . , , . . , , , .

, womp, , , ICollection (Of T):

Public Function DoStuff(Of T)(collection As ICollection(Of T), elt As T) As stuff
...
collection.Add(elt)
...
End Function

as this will allow the method user to transfer not only lists, but also all other classes that inherit from the ICollection (Of T) interface (synchronizedCollection, HashSet, LinkedList, or special ect. classes), which is really the power of OO programming.

+1
source

Source: https://habr.com/ru/post/1707794/


All Articles