自定义定义combobox的枚举名称 [英] Custom define enum names for combobox

查看:198
本文介绍了自定义定义combobox的枚举名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命名空间,其中我已声明一个枚举如下:

 命名空间IXMSoft.Business.SDK.Data 
{
using System;

public enum BaudRate
{
BR115200 = 7,
BR19200 = 4,
BR230400 = 8,
BR2400 = 1,
BR38400 = 5,
BR4800 = 2,
BR57600 = 6,
BR9600 = 3
}
}



当我在另一个命名空间中的组合框中检索这些值时,使用语句

  comboBox1.Items.Add(BaudRate.BR5700); 

它显示的值如


BR5700


我要以显示值为5700
我该怎么办?

解决方案

使用 DescriptionAttribute 适当的扩展方法可以读取。

  public enum BaudRate 
{
[描述(115200 kb)]
BR115200 = 7,
]
BR19200 = 4,
[说明(230400 kb)]
BR230400 = 8,
[说明(2400 kb)]
BR2400 = 1 ,
[说明(115200 kb)]
BR38400 = 5,
[说明(4800 kb)]
BR4800 = 2,
[ 57600 kb)]
BR57600 = 6,
[说明(9600 kb)]
BR9600 = 3
}

扩展方法:

  public static class EnumExtension 
{
///< summary>
///获取枚举的DescriptionAttribute的字符串。
///< / summary>
///< param name =value>需要描述的枚举值。< / param>
///<返回>如果设置了DescriptionAttribute,它返回它的内容。
///否则只是将原始名称作为字符串。< / returns>
public static string描述(this枚举值)
{
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& attribute.Length> 0)
{
description = attributes [0] .Description;
}

return description;
}

///< summary>
///创建具有给定Enum类的所有键和值的列表
///< / summary>
///< typeparam name =T>必须从类Enum中派生!< / typeparam>
///< return> KeyValuePair和amp; lt; Enum,string& gt;的列表。所有可用的
///给定的枚举的名称和值。< / returns>
public static IList< KeyValuePair< Enum,string>> ToList< T>()其中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& b。选择(e => new KeyValuePair< Enum,string>(e,e.Description()))
.ToArray
}

public static T GetValueFromDescription< T>(string description)其中T:struct
{
var type = typeof(T)

if(!type.IsEnum)
{
throw new ArgumentException(T must be an enum);
}

foreach(type.GetFields()中的var字段)
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute) )as DescriptionAttribute;

if(attribute!= null)
{
if(attribute.Description == description)
{
return(T)field.GetValue空值);
}
}
else
{
if(field.Name == description)
{
return(T)field.GetValue空值);
}
}
}

throw new ArgumentOutOfRangeException(description);
//或返回默认值(T);
}
}

框:通过调用

  var list = EnumExtension.ToList< BaudRate> 
myComboBox.DataSource = list;
myComboBox.ValueMember =Key;
myComboBox.DisplayMember =Value;


I have a namespace in which I have declared an enum as follows:

namespace IXMSoft.Business.SDK.Data
{
using System;

public enum BaudRate
{
    BR115200 = 7,
    BR19200 = 4,
    BR230400 = 8,
    BR2400 = 1,
    BR38400 = 5,
    BR4800 = 2,
    BR57600 = 6,
    BR9600 = 3
  }
}

When I retrieve these values in a combo box, which is in another namespace, using the statement

comboBox1.Items.Add(BaudRate.BR5700);

it shows the value as for example

"BR5700"

I want to remove BR in front and just want to display the value as "5700". What should I do?

解决方案

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&lt;Enum, string&gt; 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";

这篇关于自定义定义combobox的枚举名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆