Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to call a certain method (say method called "Mood") associated with a Enum value (e.g. Enum WorkDay : Monday, Tuesday, Wednesday etc.).
I can obviously do a select case and call certain methods as below.

Public Enum WorkDay
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
End Enum

Dim CurrentDay As Class1.WorkDay = Class1.WorkDay.Monday
    Select Case CurrentDay
        Case Class1.WorkDay.Monday
            Function_Monday()
        Case Class1.WorkDay.Tuesday
            Method_Tuesday()
        Case Class1.WorkDay.Wednesday
            Method_Wednesday()
        Case Class1.WorkDay.Thursday
            Method_Thursday()
        Case Class1.WorkDay.Friday
            Method_Friday()
    End Select

However, I have seen it done previously using an interface for the Enum to call methods in different classes. This means it's scalable by simply adding in a new class for newer Enum types, and therefore don't need to add in extra Case legs for newer Enum types (e.g. Saturday and Sunday). Can anyone possibly give me some template code for this Enum interface, as I just can't recreate it. I'm missing something!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is easily handled by the Typesafe Enum Pattern, see this article (and the previous one linked from it) give a good overview.

Enhancing the Typesafe Enum Pattern

Here is an example of how your specific issue could be handled by this pattern (converted to VB .NET):

Public Class WorkDay
   ' private constructor

   Private Sub New(day As String)
       Me.Day = day
   End Sub

  Public Day As WorkDay

  Public Sub DoDayJob()
     ' do whatever need done for that day of the week
  End Sub

  Public Shared Monday As New WorkDay("Monday")
  Public Shared Tuesday As New WorkDay("Tuesday")
  Public Shared Wednesday As New WorkDay("Wednesday")
  Public Shared Thursday As New WorkDay("Thursday")
  Public Shared Friday As New WorkDay("Friday")
End Class

 'used like this (to assign the 'Monday' value)
 Dim day = Workday.Monday

I added a single method, however the class can be as complex as it needs to be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...