我完全陷入困境,我不知道从哪里开始。我正在创建一个非常大的项目,因此我的目标是尽可能保持代码本身的清洁,并尽可能多地保持混乱。
情况就是这样。
我有一个名为Woo_Type
的类,它是我的许多派生类的父类。
Public MustInherit Class Woo_Type
Private Shared TypeList As New Dictionary(Of String, Woo_Type)
Public MustOverride Sub SetValue(ByVal val As Object)
Public MustOverride Function GetValue() As Object
Public Shared Function GetTypeFromName(ByVal name As String) As Woo_Type
Return TypeList(name)
End Function
Public Shared Sub AddType(ByVal name As String, ByVal def As Woo_Type)
TypeList.Add(name, def)
End Sub
End Class
我有许多继承自Woo_Type
的类,它们具有与此相似的结构:
Public Class Woo_tpInt
Inherits Woo_Type
Private value As Integer = 0
Public Overrides Function GetValue() As Object
Return value
End Function
Public Overrides Sub SetValue(val As Object)
value = val
End Sub
End Class
我希望能够做到这样的事情:
Woo_Type.GetTypeFromName("int")
让它返回类似于类或类似的东西......
此时我真的很困惑我想要什么,我不知道是否有人有任何建议。为了确保GetTypeFromName
正常工作,我在初始化程序子中有以下内容:
Public Sub InitializeTypes()
Woo_Type.AddType("int", Woo_tpInt)
Woo_Type.AddType("String", Woo_tpInt)
End Sub
但我很快意识到 - 这显然也无效。
所以这可能看起来令人困惑,但我基本上想知道如何更好地构建这一点以便一切正常......
答案 0 :(得分:1)
如果您想要做的是获取类型本身(而不是对象),我建议使用反射而不是尝试重新发明轮子。例如,要获取Woo_tpInt
类型,您可以执行此操作:
Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType("WindowsApplication1.Woo_tpInt") ' Change WindowsApplication1 to whatever your namespace is
如果您想使用"int"
这样的较短名称来表示"WindowsApplication1.Woo_tpInt"
,您可以创建一个字典来存储转换表,例如:
Dim typeNames As New Dictionary(Of String, String)
typeNames.Add("int", GetType(Woo_tpInt).FullName)
Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType(typeNames("int"))
答案 1 :(得分:1)
你想对结果做什么?你确定你不只是需要泛型吗?
Public Class WooType(Of T)
Public Property Value As T
End Class
Public Class Test
Public Sub Foo()
Dim int As New WooType(Of Integer)
int.Value = 42
Dim str As New WooType(Of String)
str.Value = "Forty-Two"
End Sub
End Class