.NET 列挙体に属性を付けるには?

名前属性を作成します。
Imports System.Reflection
 _
Friend Class NameAttribute
Inherits Attribute

Private _name As String

Public Property Name() As String
Get
Return Me._name
End Get
Private Set(ByVal value As String)
Me._name = value
End Set
End Property

Public Sub New(ByVal name As String)
Me.Name = name
End Sub

Public Shared Function GetName(ByVal enumValue As [Enum]) As String
Dim enumType As Type = enumValue.[GetType]()
Dim enumName As String = [Enum].GetName(enumType, enumValue)
If enumName Is Nothing Then
Return Nothing
Else
Return GetName(enumType.GetField(enumName))
End If
End Function

Private Shared Function GetName(ByVal type As MemberInfo) As String
Dim attributes As Attribute()
attributes = TryCast(type.GetCustomAttributes(GetType(NameAttribute), True), Attribute())
If attributes Is Nothing OrElse attributes.Length = 0 Then
Return Nothing
End If
Dim nameAttribute As NameAttribute = TryCast(attributes(0), NameAttribute)
Return nameAttribute.Name
End Function

End Class


別名属性を作成します。
Imports System.Reflection
 _
Friend Class AliasNameAttribute
Inherits Attribute

Private _aliasName As String

Public Property AliasName() As String
Get
Return Me._aliasName
End Get
Private Set(ByVal value As String)
Me._aliasName = value
End Set
End Property

Public Sub New(ByVal aliasName As String)
Me.AliasName = aliasName
End Sub

Public Shared Function GetAliasName(ByVal enumValue As [Enum]) As String
Dim enumType As Type = enumValue.GetType
Dim enumName As String = [Enum].GetName(enumType, enumValue)
If enumName Is Nothing Then
Return Nothing
Else
Return GetAliasName(enumType.GetField(enumName))
End If
End Function

Private Shared Function GetAliasName(ByVal type As MemberInfo) As String
Dim attributes As Attribute()
attributes = TryCast(type.GetCustomAttributes(GetType(AliasNameAttribute), True), Attribute())
If attributes Is Nothing OrElse attributes.Length = 0 Then
Return Nothing
End If
Dim nameAttribute As AliasNameAttribute = TryCast(attributes(0), AliasNameAttribute)
Return nameAttribute.AliasName
End Function

End Class


列挙体に名前と別名の属性を付けます。
Public Enum DayOfWeek As Integer
<NameAttribute("日曜日"), AliasNameAttribute("日")> _
Sun = 0
<NameAttribute("月曜日"), AliasNameAttribute("月")> _
Mon = 1
<NameAttribute("火曜日"), AliasNameAttribute("火")> _
Tue = 2
<NameAttribute("水曜日"), AliasNameAttribute("水")> _
Wed = 3
<NameAttribute("木曜日"), AliasNameAttribute("木")> _
Thu = 4
<NameAttribute("金曜日"), AliasNameAttribute("金")> _
Fri = 5
<NameAttribute("土曜日"), AliasNameAttribute("土")> _
Sat = 6
End Enum


列挙体の属性を取得するには以下のコードを書きます。
Dim dayOfWeek As DayOfWeek = DayOfWeek.Wed 

Dim name As String
name = NameAttribute.GetName(CType(dayOfWeek , [Enum]))

Dim alias As String
alias = AliasNameAttribute.GetAliasName(CType(dayOfWeek , [Enum]))

0 件のコメント: