基於對您的允許未來的枚舉值和/或類的目標的描述中,一個簡單的解決方案是使用鍵連接在基座Enum類型委託字典。
假設類的聲明是這樣的:
Public Class Class1
Public Enum WorkDay
Monday
Tuesday
Wednesday
Thursday
Friday
End Enum
Public Shared Sub Method_Monday()
End Sub
Public Shared Sub Method_Tuesday()
End Sub
Public Shared Sub Method_Wednesday()
End Sub
Public Shared Sub Method_Thursday()
End Sub
Public Shared Sub Method_Friday()
End Sub
End Class
Public Class Class2
Public Enum NotWorkDay
Saturday
Sunday
End Enum
Public Shared Sub Method_Saturday()
End Sub
Public Shared Sub Method_Sunday()
End Sub
End Class
那麼類使用上述類(一個在這種情況下WinForm的),會是這個樣子:
Public Class Form1
' declare the delegate dictionary
Private WorkMethods As New Dictionary(Of [Enum], Action)
Public Sub New()
InitializeComponent()
SetWorkMethods()
End Sub
Private Sub SetWorkMethods()
'fill the dictionary with the needed actions
WorkMethods.Add(Class1.WorkDay.Monday, New Action(AddressOf Class1.Method_Monday))
WorkMethods.Add(Class1.WorkDay.Tuesday, New Action(AddressOf Class1.Method_Tuesday))
WorkMethods.Add(Class1.WorkDay.Wednesday, New Action(AddressOf Class1.Method_Wednesday))
WorkMethods.Add(Class1.WorkDay.Thursday, New Action(AddressOf Class1.Method_Thursday))
WorkMethods.Add(Class1.WorkDay.Friday, New Action(AddressOf Class1.Method_Friday))
WorkMethods.Add(Class2.NotWorkDay.Saturday, New Action(AddressOf Class2.Method_Saturday))
WorkMethods.Add(Class2.NotWorkDay.Sunday, New Action(AddressOf Class2.Method_Sunday))
End Sub
' a helper method to retrieve and execute the action
Private Sub DoWork(day As [Enum])
Dim actionToPerform As Action = Nothing
If WorkMethods.TryGetValue(day, actionToPerform) Then
If actionToPerform IsNot Nothing Then actionToPerform()
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DoWork(Class1.WorkDay.Wednesday)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
DoWork(Class2.NotWorkDay.Saturday)
End Sub
End Class
這種用法給你有很多靈活性來配置調用的方法,而不需要在需要更改時重寫Select-Case塊。你只要在詞典中添加/刪除項目。
爲什麼不''方法'採取'WorkDay'作爲參數?那麼你只需要一個方法和一個電話。邊注:已經存在的['DayOfWeek'-枚舉(https://msdn.microsoft.com/en-us/library/system.dayofweek(V = vs.110)的.aspx),你會得到當前與['DateTime.DayOfWeek'](https://msdn.microsoft.com/en-us/library/system.datetime.dayofweek(v = vs.110)的.aspx):'昏暗陶氏= Date.Today.DayOfWeek ' –
你確定你在.net中看到過這個嗎?在Java中,枚舉可以有方法,並且枚舉方法可以實現一個接口。 – k3b
這聽起來像你正在尋找一個類的枚舉?你想要這些類來實現一個特定的接口,這樣你可以調用Class1.WorkDay.GetMood()?我在.NET中沒有見過類似的東西。也許你看過類似的東西,使用屬性? http://stackoverflow.com/questions/25323406/calling-a-method-by-enum-attribute-in-c-sharp –