vb.net:覆盖枚举的toString方法

时间:2016-02-24 11:09:02

标签: vb.net enums tostring enumeration

我想为每个枚举值覆盖toString方法。例如,我在Java中知道它可以完成如下:

public enum Language_Culture_Names{

  English {
    @Override
    public String toString() {
      return "en-GB";
    }
  },
  Spanish {
    @Override
    public String toString() {
      return "es-ES";
    }
  },
  Catalan {
    @Override
    public String toString() {
      return "ca-ES";
    }
  }

}

  System.out.println(Language_Culture_Names.English); -> returns en-GB
  System.out.println(Language_Culture_Names.Spanish); -> returns es-ES
  System.out.println(Language_Culture_Names.Catalan); -> returns ca-ES

那么如何在VB.NET中做到这一点?

2 个答案:

答案 0 :(得分:3)

理想情况下,您应该为自己定制Class,因为Enums是数字常量而不是字符串常量。

但是,如果您必须使用Enum并且正在寻找通用解决方案,那么我就是这样做的:

首先,使用以下代码向项目添加Module

Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Module Module1
    <Extension()> _
    Public Function ToString2(ByVal EnumConstant As [Enum]) As String
        Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
        Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
        If aattr.Length > 0 Then
            Return aattr(0).Description
        Else
            Return EnumConstant.ToString()
        End If
    End Function

End Module

我们将函数命名为ToString2,因为Enum.ToString已经存在,并且无法覆盖。您可以将其他任何名称命名。

现在,在您宣布Enum的班级中,使用Description属性装饰枚举成员:

Imports System.ComponentModel  '<-- be sure to include this Namespace

Public Enum Language_Culture_Names
    <Description("en-GB")> English = 1
    <Description("es-ES")> Spanish = 2
    <Description("ca-ES")> Catalan = 3
End Enum

最后转储Enum.ToString方法并使用新的Enum.ToString2方法。

e.g。

TextBox1.Text = Language_Culture_Names.English.ToString2()

HTH。

答案 1 :(得分:0)

最后我使用了type-safe-enum Pattern,如下所示:

Public NotInheritable Class LanguageCultureNames

    Private ReadOnly name As String
    Private ReadOnly value As Integer

    Public Shared ReadOnly English As New LanguageCultureNames(0, "en-GB")
    Public Shared ReadOnly Spanish As New LanguageCultureNames(1, "es-ES")
    Public Shared ReadOnly Catalan As New LanguageCultureNames(2, "ca-ES")

    Private Sub New(ByVal value As Integer, ByVal name As String)
        Me.name = name
        Me.value = value
    End Sub

    Public Overrides Function ToString() As String
        Return name
    End Function

End Class