如何检查枚举类型

时间:2015-02-28 16:00:03

标签: vb.net enums

我有一个函数可以检查参数中的枚举(我有超过7个枚举类型)并返回基于它的图像,但它不起作用。

像这样

       Enum TrophyType
            Gold
            Silver
            Bronze
        End Enum
        Enum Bla
             Bla1
             ....
        End Enum

       Public Shared Function InquireForImage(item As [Enum]) As BitmapImage
            Dim image As New BitmapImage
            Select Case item
                case TrophyType.Gold
                'return specific image
                case TrophyType.Silver
                 'return image
                case Bla.Bla1
                 'return image

            End Select
        End Function

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:4)

我建议使用不同的重载:

   Public Shared Function InquireForImage(item As TrophyType) As BitmapImage
        Select Case item
            Case TrophyType.Gold
                Return LoadImage(...)
            Case TrophyType.Silver
                Return LoadImage(...)
            ...
        End Select
   End Function

   Public Shared Function InquireForImage(item As Bla) As BitmapImage
        Select Case item
            Case Bla.bla1
                Return LoadImage(...)
            ...
        End Select
   End Function

我认为这比在代码中确定枚举类型更干净。在这里,编译器正在为您完成所有工作。确保将所有图片加载逻辑放入单独的LoadImage方法中,以便在多次InquireForImage重载时不需要重复自己。


仅供参考:如果你需要一个接受多种不同枚举类型的方法,你可以通过使用显式类型检查来区分它们:

Public Function InquireForImage(ByVal item As [Enum]) As String
    If TypeOf item Is TrophyType Then
        Select Case DirectCast(item, TrophyType)
            Case TrophyType.Gold
                Return ...
            Case TrophyType.Silver
                Return ...
            ...
        End Select

    ElseIf TypeOf item Is Bla Then
        ...

    End If
End Function

但是,一般情况下,应优先考虑过载(见上文)。

答案 1 :(得分:1)

我设法获得了很多方法(感谢@Heinzi) 一个好方法是使用这个

Public Shared Function InquireForImage(item As [Enum]) As BitmapImage
            Dim image As New BitmapImage
            Select Case item.GetType
                Case Is = GetType(TrophyType)
                    'that was my target as i wanted to use the wpf's [Resources(name)]
                    image = MainWindow.GetImageFromResources("tr_" & item.ToString())

            End Select

            Return image
        End Function
'Update -----------------------------------------------------
    Select Case item.GetType
                    Case Is = GetType(TrophyType)

                    Case Is = GetType(CamouFlages)
                        Select Case DirectCast([Enum].Parse(GetType(CamouFlages), item.ToString), CamouFlages)
                            Case CamouFlages.Default_Camo
                                imagename = "Default_Camo"
                            ' etc ....
                        End Select

                    Case Else
                        Return Nothing

                End Select

答案 2 :(得分:0)

将函数定义更改为以下内容,并将所有枚举值放在TrophyType中。

Public Shared Function InquireForImage(item As TrophyType) As BitmapImage