'What is a better alternative to using generics with types only known at runtime in this case?
Right now I can only use the Jumper class for objects of type "Something". I tried rewriting it as a generic class but ran into difficulties when actually calling it from my SomeForm class because "T" can be one of several types that I only know at runtime. I read that this means I am basically fighting the whole generics language design.
The sample code is VB but I could also work with C# answers.
Question: can this be redesigned with generics or what is a better alternative to generics in my case?
Public Class Jumper
Private _enumeratorForwards As IEnumerator(Of Something)
Public Sub JumpNext(functions As FunctionCombi)
Forwards(functions.SelectorFunc)
End Sub
Private Iterator Function Forwards(selectorFunc As Func(Of Something, Boolean)) As IEnumerable(Of Something)
End Class
Public Class FunctionCombi
Public Property SelectorFunc As Func(Of Something, Boolean)
Sub New(_selectorFunc As Func(Of Something, Boolean))
SelectorFunc = _selectorFunc
End Sub
End Class
Public Class SomeForm
'x and y would be different types
Private _functionCombis As New Dictionary(Of SomeEnum, FunctionCombi) From {
{SomeEnum.A, New FunctionCombi(Function(x) RunSomeFunction(x)},
{SomeEnum.B, New FunctionCombi(Function(y) RunSomeOtherFunction(y))}
Private Sub SomeHandler(sender as object, e as EventArgs)
For i = 1 To [Enum].GetValues(GetType(SomeEnum)).Length
'The type I would need here differs and I only know it at runtime
Dim functionInfo As FunctionCombi = Nothing
If Not _functionCombis.TryGetValue(i, functionInfo) Then Continue For
Dim jumper As Jumper = sender.Tag(2)
Next
End Sub
End Class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
