Tôi thấy rằng cách tốt nhất để tôi làm điều này là sử dụng thuộc tính System.ComponentModel.Description trên các giá trị enum.
Dưới đây là một ví dụ:
using System.ComponentModel;
public enum ActionCode
{
[Description("E")]
Edit,
[Description("D")]
Delete,
[Description("R")]
Restore
}
Sau đó, để sử dụng nó, tạo ra một phương pháp khuyến nông trên một lớp tĩnh như vậy:
Edit: Tôi viết lại mã gốc là một phương pháp khuyến nông chung trên một lớp thực hiện IConvertible
(Enum
triển khai giao diện này, vì vậy nó hoạt động theo cách chúng ta cần). Dưới đây là một phương pháp chung mà hoạt động trên tất cả enums:
public static string GetDescription<T>(this T e) where T : IConvertible
{
if (e is Enum)
{
Type type = e.GetType();
Array values = System.Enum.GetValues(type);
foreach (int val in values)
{
if (val == e.ToInt32(CultureInfo.InvariantCulture))
{
var memInfo = type.GetMember(type.GetEnumName(val));
var descriptionAttribute = memInfo[0]
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
if (descriptionAttribute != null)
{
return descriptionAttribute.Description;
}
}
}
}
return null; // could also return string.Empty
}
Vì vậy, để có được chuỗi kết hợp với enum của chúng tôi ở trên, chúng ta có thể sử dụng đoạn mã sau:
using Your.Extension.Method.Namespace;
...
ActionCode action = ActionCode.Edit;
string actionDescription = action.GetDescription();
// value of actionDescription will be "E"
Dưới đây là một mẫu Enum:
public enum TestEnum
{
[Description("This is test 1")]
Test1,
[Description("This is test 2")]
Test2,
[Description("This is test 3")]
Test3
}
đây là đoạn mã để xem mô tả:
TestEnum test = TestEnum.Test2;
var testDescription = test.GetDescription();
Kết quả sẽ là:
"This is test 2"
tôi muốn đi trước và đăng các phương pháp chung chung vì nó là nhiều hơn nữa hữu ích. Nó ngăn cản bạn phải viết một phần mở rộng tùy chỉnh cho tất cả các enums của bạn.
Tôi lướt qua nhưng không thấy bất kỳ điều gì về việc gán giá trị chuỗi tại đó. – ediblecode