【问题标题】:Abstract Enum selection box抽象枚举选择框
【发布时间】:2009-02-04 18:34:45
【问题描述】:

我正在尝试制作一个可以采用枚举类型的函数,向用户显示所有可能的选择,让他们选择一个然后将其传回。泛型不允许您限制枚举。我的代码可以来回转换,但我希望它接受并返回相同的枚举类型。

此代码有效,但不如我想的那么好:

Public Function getEnumSelection(ByVal owner As Windows.Forms.IWin32Window, ByVal sampleValue As [Enum], ByVal subtitle As String) As String

    Dim names As String() = [Enum].GetNames(sampleValue.GetType)
    Using mInput As New dlgList
        mInput.ListBox1.Items.Clear()
        For Each name As String In names
            mInput.ListBox1.Items.Add(name)
        Next
        mInput.ShowDialog(owner)
        Return mInput.ListBox1.SelectedItem.ToString
    End Using
End Function

在它运行后,我可以 [Enum].parse 在调用者上直接解析为枚举类型,因为我可以在那里访问它,但我想消除这个手动步骤。

我希望能够返回相同的枚举类型,或者至少将解析返回到我收到的值并将其转换到此函数中,但它似乎不允许这一行。 暗淡结果 As Object = [Enum].Parse(GetType(sampleValue), mInput.ListBox1.SelectedItem.ToString, True)

它说 sampleValue 不是一个类型。那么...如何获取要解析的 sampleValue 的类型?

或者是否有另一种方法可以轻松且通用地允许用户选择枚举值,而无需为每个枚举手动编码映射函数?

【问题讨论】:

    标签: .net vb.net enums abstraction


    【解决方案1】:

    首先要回答最小的问题,您可以通过调用 sampleValue.GetType() 来获取对象的类型,就像您已经在函数的第一行中所做的那样。 GetType 既是关键字又是 Object 类的方法 - 第一个获取类型的类型(有点重言式),第二个获取对象实例的类型。

    至于更大的问题,我建议使用对参数的约束稍微宽松的泛型方法:让它接受任何结构,而不仅仅是枚举。你失去了一点类型安全,但我认为这是一个不错的权衡。如果有人传入一个非枚举结构,他们会在运行时得到一个 ArgumentException,所以你不会从函数中得到垃圾。

    Public Function getEnumSelection(Of T As Structure)(ByVal owner As Windows.Forms.IWin32Window, ByVal subtitle As String) As T
        Dim names As String() = [Enum].GetNames(GetType(T))
        Using mInput As New dlgList
            mInput.ListBox1.Items.Clear()
            For Each name As String In names
                mInput.ListBox1.Items.Add(name)
            Next
            mInput.ShowDialog(owner)
            Return DirectCast([Enum].Parse(GetType(T), mInput.ListBox1.SelectedItem.ToString), T)
        End Using
    End Function
    

    【讨论】:

    • 我喜欢它的以下更改 Return DirectCast([Enum].Parse(GetType(T), mInput.ListBox1.SelectedItem.ToString), T) 和公共函数 getEnumSelection(Of T As Structure) (ByVal 所有者 As Windows.Forms.IWin32Window, ByVal subtitle As String) As T
    • 是的,对不起,这就是我的意思——我的草率复制粘贴。我将编辑帖子。
    猜你喜欢
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-07-03
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多