简体   繁体   English

如何从字符串表示形式创建枚举? C#

[英]how do I create an enum from a string representation? c#

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: 然后在代码behid中执行以下操作:

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"? 我的问题是我不知道如何将字符串转换为枚举列表,所以“ 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 我真的很希望能够传递一个整洁的列表

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));
}

您需要查看System.Enum.Parse方法。

Enum.Parse is the canonical way to parse a string to get an enum: Enum.Parse是解析字符串以获取枚举的规范方法:

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. 但是,您的属性当前为MS[]类型MS[]value变量将不是字符串。 I suspect you'll need to make your property a string, and parse it there, storing the results in a MS[] . 我怀疑您需要将您的属性设置为字符串,然后在其中进行解析,并将结果存储在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. 我不知道您是否需要直接公开数组本身-这取决于您要执行的操作。

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) (更新了我的代码,因为我误读了您的代码)

用[Flags]属性标记您的枚举,然后组合标志而不是枚举值数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM