Is there an elegant way to write this code?

I have inherited some code, and it makes me cringe when I look at it. Is there a more elegant way to write the following?

Dim myItem As DTO.MyBaseClass = Nothing
Dim myType As String = GetTypeString()
Select Case myType
  Case Is = "Case1"
    myItem = Bus.BusManager(Of DTO.MyClass1).Read()
  Case Is = "Case2"
    myItem = Bus.BusManager(Of DTO.MyClass2).Read()
'... etc etc for 30 lines

Is there a way to make a map from a string to a class type and then just have such a string? Or something similar?

myItem = Bus.BusManager(Of MappingDealy(myType)).Read()
+5
source share
3 answers

Since it BusManageris generic, the type you pass in Of <type>must be specified at compile time. This is not like a traditional parameter that you can change at runtime.

, , , BusManager. , , Generic, , , , , . , BusManager, ?

@jmoreno, , , . :

Imports System.Reflection
Imports System.IO

Public Class ObjectFactory
    Private Shared Function CreateObjectFromAssembly(ByVal assembly As Assembly, ByVal typeName As String) As Object
        ' resolve the type
        Dim targetType As Type = assembly.GetType(typeName)
        If targetType Is Nothing Then
            Throw New ArgumentException("Can't load type " + typeName)
        End If

        ' get the default constructor and instantiate
        Dim types(-1) As Type
        Dim info As ConstructorInfo = targetType.GetConstructor(types)
        Dim targetObject As Object = info.Invoke(Nothing)
        If targetObject Is Nothing Then
            Throw New ArgumentException("Can't instantiate type " + typeName)
        End If

        Return targetObject
    End Function

    Public Shared Function CreateObject(ByVal typeName As String) As Object
        Return CreateObjectFromAssembly(Assembly.GetExecutingAssembly, typeName)
    End Function

    Public Shared Function CreateObject(ByVal typeName As String, ByVal assemblyFileName As String) As Object
        Dim assemblyFileInfo = New FileInfo(assemblyFileName)
        If assemblyFileInfo.Exists Then
            Return CreateObjectFromAssembly(Reflection.Assembly.LoadFrom(assemblyFileName), typeName)
        Else
            Throw New ArgumentException(assemblyFileName + " cannot be found.")
        End If
    End Function

End Class

, , . , typeName, .

factory , :

Dim myItem as DTO.MyBaseClass = ObjectFactory.CreateObject("DTO." & GetTypeString())
+1

, Case Is = Nothing. , :

Dim myItem As DTO.MyBaseClass
Select Case GetTypeString()
    Case "Case1"
        myItem = Bus.BusManager(Of DTO.MyClass1).Read()
    ' etc etc

, , , . Imports DTO 124 , 120 .

0
0

All Articles