Jak korzystać z funkcji znakowania.Coś jak:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
Trzeba by napisać atrybut StringValue jak:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
Aby go:
Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
For Each val As [Enum] In [Enum].GetValues(enumType)
Dim fi As FieldInfo = enumType.GetField(val.ToString())
Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
Dim attr As StringValueAttribute = attributes(0)
If attr.Value = value Then
Return val
End If
Next
Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function
Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function
a następnie wezwanie do zdobycia wyliczenia (z użyciem atrybut ciągu znaków):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
Aby uzyskać wartość "atrybut" out (usunięty obsługi 'nic' dla jasności):
Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
End Function
Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
End Function
i wezwanie, aby uzyskać atrybut ciąg (używając Enum):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
Rozwiązanie konstrukcyjne (przez Slai) realizuje to samo w 4 liniach kodu. –
@JonHarbour Erm ... Nie. Nie działa. Po prostu używa ciągów, więc nie jest tak bezpieczny, jak mocno wpisany wzorzec wyliczeniowy, nie można go rozszerzyć i nie można dodawać jawnych konwersji. Ponadto nie widzę sensu w używaniu struktury nad modułem w tym przypadku. – sloth
Jeśli chcesz porównać takie obiekty w 'Select Case', powinieneś zrobić' Key' Public i porównać używając '.Key'. – mbomb007