在C#中,description属性显示枚举的描述和值。

huangapple go评论66阅读模式
英文:

description attribute in c# shows the description and the value from enum

问题

I want it to show only the text that is within the description area, how can I do that? Thanks!

我希望它只显示在描述区域内的文本,我该如何做到?谢谢!

英文:

Im trying to present a description of enum and it presents me the description and the value.
i want it to show only the text that is within the description area, how can i do that? thanks!
this is the enum:
[Description("Choclate Bar")] choclateBar,
[Description("Caffe Protein Bar")] CafeProteinBar,
[Description("Vanilla Cookie")] vanillaCookie,

this is the code im using to present the enums in a combobox
enter image description here
and the second picture is how its shows.
enter image description here

i want it to show in the combobox the values that within the description ("Choclate Bar", ...)

答案1

得分: 1

以下是您要翻译的内容:

以下是一个在ComboBox中呈现枚举的示例,其中第一项用于提示用户进行选择。

枚举

public enum BookCategories
{
    [Description("选项")]
    Select = 0,
    [Description("太空旅行")]
    SpaceTravel = 1,
    [Description("冒险")]
    Adventure = 2,
    [Description("流行体育")]
    Sports = 3,
    [Description("汽车")]
    Automobile = 4,
    [Description("使用C#编程")]
    Programming = 5
}

用于在ComboBox中呈现的模型

public class BookContainer
{
    public Enum Name { get; set; }
    public string Description { get; set; }
    // 用于在ComboBox中显示
    public override string ToString() => Description;
}

获取枚举描述的代码

public static class EnumHelper
{
    /// <summary>
    /// 创建一个KeyValuePair,其中Key是描述,Value是枚举值
    /// </summary>
    /// <typeparam name="T">要处理的枚举</typeparam>
    public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>
        Enum.GetValues(typeof(T)).Cast<T>()
            .Cast<Enum>()
            .Select(value => new KeyValuePair<string, Enum>(
                (Attribute.GetCustomAttribute(value.GetType()
                        .GetField(value.ToString())!,
                    typeof(DescriptionAttribute)) as DescriptionAttribute)!
                .Description, value))
            .ToList();

    public static List<BookContainer> Container<T>()
    {
        List<KeyValuePair<string, Enum>> data = GetItemsAsDictionary<T>();
        return data.Select(category 
            => new BookContainer() { Name = category.Value, Description = category.Key })
            .ToList();
    }
}

表单代码,一个ComboBox,两个按钮

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }

    private void OnShown(object? sender, EventArgs e)
    {
        categoriesComboBox.DataSource = EnumHelper.Container<BookCategories>();
    }

    private void CurrentButton_Click(object sender, EventArgs e)
    {
        BookContainer container = (categoriesComboBox.SelectedItem as BookContainer)!;
        if (Equals(container.Name, BookCategories.Select))
        {
            MessageBox.Show("请选择一个项目");
        }
        else
        {
            MessageBox.Show($"选择是 {container.Name}");
        }
    }

    private void SetCurrentButton_Click(object sender, EventArgs e)
    {
        // 这里是如何设置需要的选定索引
        categoriesComboBox.SelectedIndex = 
            categoriesComboBox.FindString(BookCategories.Adventure.ToString());
    }
}

在C#中,description属性显示枚举的描述和值。

英文:

The following presents an Enum in a ComboBox where the first item is to prompt the user for a selection.

Enum

public enum BookCategories
{
    [Description(&quot;Options&quot;)]
    Select = 0,
    [Description(&quot;Space Travel&quot;)]
    SpaceTravel = 1,
    [Description(&quot;Adventure&quot;)]
    Adventure = 2,
    [Description(&quot;Popular sports&quot;)]
    Sports = 3,
    [Description(&quot;Cars&quot;)]
    Automobile = 4,
    [Description(&quot;Programming with C#&quot;)]
    Programming = 5
}

Model for presenting in a ComboBox

public class BookContainer
{
    public Enum Name { get; set; }
    public string Description { get; set; }
    // for displaying in ComboBox
    public override string ToString() =&gt; Description;
}

Code to get descriptions for the Enum

public static class EnumHelper
{
    /// &lt;summary&gt;
    /// Create a &lt;see cref=&quot;KeyValuePair&quot;/&gt; where Key is the description,
    /// Value the enum value
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;enum to work with&lt;/typeparam&gt;
    public static List&lt;KeyValuePair&lt;string, Enum&gt;&gt; GetItemsAsDictionary&lt;T&gt;() =&gt;
        Enum.GetValues(typeof(T)).Cast&lt;T&gt;()
            .Cast&lt;Enum&gt;()
            .Select(value =&gt; new KeyValuePair&lt;string, Enum&gt;(
                (Attribute.GetCustomAttribute(value.GetType()
                        .GetField(value.ToString())!,
                    typeof(DescriptionAttribute)) as DescriptionAttribute)
                !.Description, value))
            .ToList();


    public static List&lt;BookContainer&gt; Container&lt;T&gt;()
    {
        List&lt;KeyValuePair&lt;string, Enum&gt;&gt; data = GetItemsAsDictionary&lt;T&gt;();
        return data.Select(category 
            =&gt; new BookContainer() { Name = category.Value, Description = category.Key })
            .ToList();
    }
}

Form code, a ComboBox, two buttons

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Shown += OnShown;
    }

    private void OnShown(object? sender, EventArgs e)
    {
        categoriesComboBox.DataSource = EnumHelper.Container&lt;BookCategories&gt;();
    }

    private void CurrentButton_Click(object sender, EventArgs e)
    {
        BookContainer container = (categoriesComboBox.SelectedItem as BookContainer)!;
        if (Equals(container.Name, BookCategories.Select))
        {
            MessageBox.Show(&quot;Please make a selection&quot;);
        }
        else
        {
            MessageBox.Show($&quot;Selection is {container.Name}&quot;);
        }
    }

    private void SetCurrentButton_Click(object sender, EventArgs e)
    {
        // here is how to set the selected index if needed
        categoriesComboBox.SelectedIndex = 
            categoriesComboBox.FindString(BookCategories.Adventure.ToString());
    }
}

在C#中,description属性显示枚举的描述和值。

huangapple
  • 本文由 发表于 2023年5月29日 23:44:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定