2009-02-04 240 views
0

我想做一个函数,可以采取枚举类型,显示所有可能的选择给用户,让他们选择一个,然后将其传回。泛型不允许你限制枚举。我有代码工作会来回转换,但我希望它接受并返回相同的枚举类型。抽象枚举选择框

此代码的工作,但没有得到很好的,因为我想:

公共功能getEnumSelection(BYVAL所有者Windows.Forms.IWin32Window,BYVAL sampleValue为[枚举],字幕BYVAL作为字符串)作为字符串

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 

它运行后,我可以[枚举] .parse直接调用者的枚举类型,因为我有权访问它,但我想消除这个手动步骤。

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

它说sampleValue不是一个类型。所以...我如何获得sampleValue的类型来解析?

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

回答

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 
+0

我用下面的喜欢它改变 返回DirectCast([枚举] .Parse(的GetType(T),mInput.ListBox1.SelectedItem.ToString),T) 和 公共功能getEnumSelection(效应的T作为结构)(BYVAL所有者作为Windows.Forms.IWin32Window,ByVal字幕作为字符串)作为T – Maslow 2009-02-11 12:26:59