0

我完全陷入了困境,我不知道从这里去哪里。我正在创建一个非常大的项目,所以我的目标是保持代码本身尽可能干净,并尽可能多地避免混合。

这是情况。

我有一个名为 的类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正常工作,我在 Initializer 子中有以下内容:

Public Sub InitializeTypes()
    Woo_Type.AddType("int", Woo_tpInt)
    Woo_Type.AddType("String", Woo_tpInt)
End Sub

但我很快意识到——这显然也行不通。

所以这可能看起来令人困惑,但我基本上想知道如何更好地构建它,以便一切正常......

4

2 回答 2

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"mean "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"))
于 2012-07-06T14:25:34.347 回答
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
于 2012-07-06T14:27:38.667 回答