2

我有一个用户控件,它实际上是下拉列表的包装器。

我设置了这样的类型:

public Type ListType { get; set; }

然后尝试基于此类型创建下拉列表项。

这是我的第一次尝试:

    void SetOptions()
    {
        DropDownList.Items.Clear();

        var options = Enum.GetNames(ListType).ToList();

        options.ThrowNullOrEmpty("options");

        foreach (var s in options)
        {
            var e = Enum.Parse(ListType, s) as Enum;

            var item = new ListItem(e.Description(), s);

            DropDownList.Items.Add(item);
        }
    }

但是,我想知道是否可以这样做:

    void SetOptions()
    {
        DropDownList.Items.Clear();

        var options = Enum.GetValues(ListType); // need to cast this to type of ListType

        foreach (var o in options)
        {
            var item = new ListItem(o.Description(), o.ToString());

            DropDownList.Items.Add(item);
        }
    }

只是无法弄清楚如何将值列表转换为正确的枚举类型。

有任何想法吗?

4

1 回答 1

2

你可以这样做:

void SetOptions()
{
    DropDownList.Items.Clear();

    var options = Enum.GetValues(ListType); // need to cast this to type of ListType

    foreach (var o in options)
    {
        var item = new ListItem(o.Description(), o.ToString());
        item.Tag = o;

        DropDownList.Items.Add(item);
    }
}

然后,您可以从选择的任何列表项的 Tag 属性中获取类型。

于 2013-07-18T18:36:02.277 回答