Select(switch) Case更优雅的实现: 使用数组+Action

有的时候可能会写出形如这样的代码:

Public Class Class1
    Enum CommandType
        A
        B
        C
    End Enum

    Private _blahblah, _blbhblbh, _blchblch

    Public Sub process(xxx As CommandType)
        Select Case xxx
            Case CommandType.A
                Me.xxx(Me._blahblah, Me._blbhblbh)
            Case CommandType.B
                Me.yyy(Me._blahblah, Me._blbhblbh, Me._blchblch)
            Case CommandType.C
                Me.zzz(Me._blahblah)
            Case Else
                Throw New Exception()
        End Select
    End Sub

    Private Sub xxx(a, b)
        '...
    End Sub

    Private Sub yyy(a, b, c)
        '...
    End Sub

    Private Sub zzz(a)
        '...
    End Sub

End Class

这极其不优雅, 而且Select会查找一次或多次, 这简直无法容忍。

于是我们知道有数组(或者字典)和Action这种东西, 于是将代码变成了如下这个样子。

Public Class Class1
    Enum CommandType
        A
        B
        C
        _max
    End Enum

    Private _blahblah, _blbhblbh, _blchblch

    Public Shared Processors As Action(Of Class1)() = Nothing

    Public Shared Sub InitProcessor()
        If Processors IsNot Nothing Then
            Return
        End If
        ReDim Processors(CommandType._max)
        Processors(CommandType.A) =
            Sub(_Me As Class1)
                _Me.xxx(_Me._blahblah, _Me._blbhblbh)
            End Sub
        Processors(CommandType.B) =
            Sub(_Me As Class1)
                _Me.yyy(_Me._blahblah, _Me._blbhblbh, _Me._blchblch)
            End Sub
        Processors(CommandType.C) =
          Sub(_Me As Class1)
              _Me.zzz(_Me._blahblah)
          End Sub
    End Sub

    Public Sub process(xxx As CommandType)
        InitProcessor()
        Dim SelectedProcessor As Action(Of Class1) = Processors(xxx)
        If SelectedProcessor IsNot Nothing Then
            SelectedProcessor(Me)
        Else
            Throw New Exception()
        End If
    End Sub

    Private Sub xxx(a, b)
        '...
    End Sub

    Private Sub yyy(a, b, c)
        '...
    End Sub

    Private Sub zzz(a)
        '...
    End Sub

End Class

通过在Enum最后加了个_max可以获得该枚举的最大长度, 然后使用了Shared的Action数组来节约内存, 并且使用Action(Of Class1)提供lambda表达式里面对自己实例的引用。

数组一次定位, 于是比Select Case快一些。

发表评论

注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)

本文链接:https://twd2.me/archives/4402QrCode