我有一个相当无意义的代码列表,我正在使用VB.NET Windows应用程序进行处理。 对于我正在编写的用于处理这些代码的业务逻辑,我想使用有意义的常量(如ServiceNotCovered或MemberNotEligible )而不是原始代码(如"SNCV"和"MNEL" )。
据我所知,枚举只能映射到数值,而不是字符串。 所以我能够想到的最好的是一个静态类,它将常量暴露为内部设置为等于代码值的静态只读字符串字段,如下所示。
Public Class MyClass private _reasonCode as String() Public Property ReasonCode() As String 'Getter and Setter... End Property Public Class ReasonCodeEnum Private Sub New() End Sub Public Shared ReadOnly ServiceNotCovered As String = "SNCV" Public Shared ReadOnly MemberNotEligible As String = "MNEL" 'And so forth... End Class End Class 'Calling method Public Sub ProcessInput() Dim obj As New MyClass() Select Case obj.ReasonCode Case MyClass.ReasonCodeEnum.ServiceNotCovered 'Do one thing Case MyClass.ReasonCodeEnum.MemberNotEligible 'Do something different 'Other enum value cases and default End Select End Sub在上面的例子中,如果我可以将MyClass.ReasonCode定义为ReasonCodeEnum类型,那么将会很好,但是接下来我必须使ReasonCodeEnum成为非静态类并给它一种设置和返回值的方法。
我想知道的是,是否有一种方法可以使用内置的Enum功能来完成我正在做的事情,或者如果没有,是否有任何标准设计模式用于这种类型的事情。
I have a list of rather meaningless codes that I'm processing with a VB.NET Windows application. For the business logic I'm writing to process those codes, I'd like to use meaningful constants (like ServiceNotCovered or MemberNotEligible) instead of the original codes (like "SNCV" and "MNEL").
As far as I can tell, Enums can only map to numeric values, not to strings. So the best I've been able to come up with is a static class that exposes the constants as static readonly string fields that are internally set equal to the code values, as follows.
Public Class MyClass private _reasonCode as String() Public Property ReasonCode() As String 'Getter and Setter... End Property Public Class ReasonCodeEnum Private Sub New() End Sub Public Shared ReadOnly ServiceNotCovered As String = "SNCV" Public Shared ReadOnly MemberNotEligible As String = "MNEL" 'And so forth... End Class End Class 'Calling method Public Sub ProcessInput() Dim obj As New MyClass() Select Case obj.ReasonCode Case MyClass.ReasonCodeEnum.ServiceNotCovered 'Do one thing Case MyClass.ReasonCodeEnum.MemberNotEligible 'Do something different 'Other enum value cases and default End Select End SubIn the example above, it would be nice if I could define MyClass.ReasonCode as having type ReasonCodeEnum, but then I'd have to make ReasonCodeEnum a nonstatic class and give it a way of setting and returning a value.
What I'm wondering is whether there's a way to use the built-in Enum functionality to do what I'm doing, or if not, are there any standard design patterns for this type of thing.
最满意答案
你可以使用我在这里发布的代码在VB.Net中模拟任何类型的自定义枚举: 使用反射获取类型的静态字段值
You can emulate custom enums of any type in VB.Net using the code I posted here: Getting static field values of a type using reflection
更多推荐
发布评论