枚举和接口 [英] Enum's and Interfaces

查看:221
本文介绍了枚举和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用与枚举值相关联的某种方法(称为心情),例如Enum WorkDay:星期一,星期二,星期三等) 。

我可以明显地做一个选择案例,并调用某些方法如下。

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

但是,我以前使用枚举调用不同类的方法。这意味着它可以通过简单地为新的 Enum 类型添加一个新类,因此不需要为新的枚举添加额外的Case脚类型(例如星期六和星期日)。任何人都可以给我这个 Enum 界面的一些模板代码,因为我无法重新创建它。我错过了一些东西!

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!

推荐答案

这可以很容易地被Typesafe Enum Pattern处理,看到这篇文章从它)给出一个很好的概述。

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

增强类型安全枚举模式

以下是一个示例,说明您的具体问题如何处理通过此模式(转换为VB .NET):

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.

这篇关于枚举和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆