枚举和接口

编程入门 行业动态 更新时间:2024-10-25 02:22:48
本文介绍了枚举和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图调用与枚举值相关联的某种方法(称为心情),例如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.

更多推荐

枚举和接口

本文发布于:2023-11-04 05:39:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!