🌷

VB.NetでEnumに日本語名属性を付加する例

2024/01/04に公開
''' <summary>
''' 属性クラスを定義する
''' </summary>
<AttributeUsage(AttributeTargets.Field, AllowMultiple:=False, Inherited:=False)>
Public Class EnumJpAttribute Inherits Attribute
Private _literal As String
Public Sub New(ByVal literal As String)
    _literal = literal
End Sub

Public Shared Function ToStringJp(ByVal value As Object) As String
    Dim enumType As Type = value.GetType()
    Dim enumName As String = [Enum].GetName(enumType, value)
    Dim fi As Reflection.FieldInfo = enumType.GetField(enumName)
    Dim attrs As EnumJpAttribute() = DirectCast(fi.GetCustomAttributes(GetType(EnumJpAttribute), False), EnumJpAttribute())
    Return attrs(0)._literal
End Function
End Class

''' <summary>
''' Enum定義で、属性を付加する 
''' </summary>
Public Enum SexType As Integer
<EnumJpAttribute("男性")>
Male
<EnumJpAttribute("女性")>
Female
End Enum

''' <summary>
''' 使い方
''' </summary>
Public Class Sample
Public Function Sample() As String
    Return EnumJpAttribute.ToStringJp(SexType.Male)
End Function
End Class

Discussion