use the DescriptionAttribute
and an appropriate extension method to read it out.
public enum BaudRate
{
[Description("115200 kb")]
BR115200 = 7,
[Description("19200 kb")]
BR19200 = 4,
[Description("230400 kb")]
BR230400 = 8,
[Description("2400 kb")]
BR2400 = 1,
[Description("115200 kb")]
BR38400 = 5,
[Description("4800 kb")]
BR4800 = 2,
[Description("57600 kb")]
BR57600 = 6,
[Description("9600 kb")]
BR9600 = 3
}
The extension method:
public static class EnumExtension
{
/// <summary>
/// Gets the string of an DescriptionAttribute of an Enum.
/// </summary>
/// <param name="value">The Enum value for which the description is needed.</param>
/// <returns>If a DescriptionAttribute is set it return the content of it.
/// Otherwise just the raw name as string.</returns>
public static string Description(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string description = value.ToString();
FieldInfo fieldInfo = value.GetType().GetField(description);
DescriptionAttribute[] attributes =
(DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
description = attributes[0].Description;
}
return description;
}
/// <summary>
/// Creates an List with all keys and values of a given Enum class
/// </summary>
/// <typeparam name="T">Must be derived from class Enum!</typeparam>
/// <returns>A list of KeyValuePair<Enum, string> with all available
/// names and values of the given Enum.</returns>
public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be an enum");
}
return (IList<KeyValuePair<Enum, string>>)
Enum.GetValues(type)
.OfType<Enum>()
.Select(e => new KeyValuePair<Enum, string>(e, e.Description()))
.ToArray();
}
public static T GetValueFromDescription<T>(string description) where T : struct
{
var type = typeof(T);
if(!type.IsEnum)
{
throw new ArgumentException("T must be an enum");
}
foreach(var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if(attribute != null)
{
if(attribute.Description == description)
{
return (T)field.GetValue(null);
}
}
else
{
if(field.Name == description)
{
return (T)field.GetValue(null);
}
}
}
throw new ArgumentOutOfRangeException("description");
// or return default(T);
}
}
At the and you can simply apply this to your combo box by calling:
var list = EnumExtension.ToList<BaudRate>();
myComboBox.DataSource = list;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Value";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…