Cách sử dụng Gắn thẻ.Một cái gì đó như:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
Bạn sẽ phải viết các thuộc tính stringValue như:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
Để có được nó ra:
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
Và sau đó là một cuộc gọi để có được những Enum (sử dụng thuộc tính chuỗi):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
Để có được "Thuộc tính" giá trị ra (tháo xử lý 'Không có gì' cho rõ ràng):
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
Và cuộc gọi để có được những thuộc tính chuỗi (sử dụng Enum):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
Giải pháp cấu trúc (bởi Slai) hoàn thành điều tương tự trong 4 dòng mã. –
@JonHarbour Erm ... Không. Không. Nó chỉ sử dụng các chuỗi, do đó, nó không phải là loại an toàn như các mẫu enum mạnh mẽ gõ, nó không thể được mở rộng, và bạn không thể thêm chuyển đổi rõ ràng. Ngoài ra, tôi không thấy một điểm trong việc sử dụng một cấu trúc trên một mô-đun trong trường hợp này. – sloth
Nếu bạn muốn so sánh các đối tượng như thế này trong trường hợp 'Chọn trường hợp ', bạn nên đặt' Khóa công khai' và so sánh bằng cách sử dụng '.Key'. – mbomb007