如何从字符串表示形式创建枚举? C# [英] how do I create an enum from a string representation? c#

查看:80
本文介绍了如何从字符串表示形式创建枚举? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im试图从用户控件传回属于枚举的字符串列表,例如:

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

我的问题是我不知道该如何旋转字符串进入一个枚举列表,那么 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

推荐答案

Enum.Parse 是解析字符串以获取枚举的规范方法:

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.

但是,您的媒体资源当前的类型为 MS [] -设置器中的 value 变量不会是字符串。我怀疑您需要将您的媒体资源设置为字符串,然后在其中进行解析,然后将结果存储在 MS [] 中。例如:

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.

这篇关于如何从字符串表示形式创建枚举? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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