Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

.net - Enum's and Interfaces

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...