gpt4 book ai didi

vb.net - 有没有一种优雅的方式来编写这段代码?

转载 作者:行者123 更新时间:2023-12-03 00:38:08 24 4
gpt4 key购买 nike

我继承了一些代码,当我看到它时,它让我感到畏缩。有没有更优雅的方式来编写以下内容?

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

有没有办法制作从字符串到类类型的映射,然后只有这样一行?或者类似的东西?

myItem = Bus.BusManager(Of MappingDealy(myType)).Read()

最佳答案

BusManager是一个泛型,您传递给 Of <type> 的类型必须在编译时指定。它不像传统参数那样可以在运行时更改。

从您列出的代码中不清楚 BusManager事实上确实如此。如果它所做的只是创建泛型类型的实例,那么创建它的人可能并不真正理解泛型。你有能力如何返工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

在生产应用程序中,我可能会将所有这些方法的返回类型设置为我的基类或接口(interface)。只需确保您输入完整的 typeName包括命名空间。

有了该工厂类,代码的优雅版本将如下所示:

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

关于vb.net - 有没有一种优雅的方式来编写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6117932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com