how do I create an enum from a string representati

2019-06-13 17:49发布

im trying to pass back from a user control a list of strings that are part of an enum, like this:

<bni:products id="bnProducts" runat="server" ProductsList="First, Second, Third"  />

and in the code behid do something like this:

public enum MS 
    {
        First = 1,
        Second,
        Third
    };
    private MS[] _ProductList;
    public MS[] ProductsList
    {
        get
        {
            return _ProductList;
        }
        set
        {
            _ProductList = how_to_turn_string_to_enum_list;
        }
    }

my problem is I dont know how to turn that string into a list of enum, so what should be "how_to_turn_string_to_enum_list"? or do you know of a better way to use enums in user controls? I really want to be able to pass a list that neat

5条回答
叼着烟拽天下
2楼-- · 2019-06-13 18:00

You need to look at the System.Enum.Parse method.

查看更多
Anthone
3楼-- · 2019-06-13 18:01
string[] stringValues = inputValue.Split(',');

_ProductList = new MS[stringValues.Length];

for (int i=0;i< stringValues.Length;i++)
  _ProductList[i] = (MS) Enum.Parse(typeof(MS), stringValues[i].Trim());

(updated my code because I misread your code)

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-13 18:13

This is a short solution, but it doesn't cover some very important things like localization and invalid inputs.

private static MS[] ConvertStringToEnumArray(string text)
{
    string[] values = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
    return Array.ConvertAll(values, value => (MS)Enum.Parse(typeof(MS), value));
}
查看更多
Lonely孤独者°
5楼-- · 2019-06-13 18:23

Mark your enum with the [Flags] attribute, and combine flags instead of an array of enum values.

查看更多
太酷不给撩
6楼-- · 2019-06-13 18:25

Enum.Parse is the canonical way to parse a string to get an enum:

MS ms = (MS) Enum.Parse(typeof(MS), "First");

but you'll need to do the string splitting yourself.

However, your property is currently of type MS[] - the value variable in the setter won't be a string. I suspect you'll need to make your property a string, and parse it there, storing the results in a MS[]. For example:

private MS[] products;

public string ProductsList
{
    get
    {
        return string.Join(", ", Array.ConvertAll(products, x => x.ToString()));
    }
    set
    {
        string[] names = value.Split(',');
        products = names.Select(name => (MS) Enum.Parse(typeof(MS), name.Trim()))
                        .ToArray();
    }
}

I don't know whether you'll need to expose the array itself directly - that depends on what you're trying to do.

查看更多
登录 后发表回答