从字符串获取一个枚举的场 [英] Get an enumerated field from a string

查看:95
本文介绍了从字符串获取一个枚举的场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个奇怪的这一点位。请原谅下面的半伪code。我有枚举值的列表。比方说,例如,像这样:

Bit of a strange one this. Please forgive the semi-pseudo code below. I have a list of enumerated values. Let's say for instance, like so:

public enum Types
    {
       foo = 1,
       bar = 2,
       baz = 3
    }

这将成为,恭敬,在code:

Which would become, respectfully, in the code:

Types.foo
Types.bar
Types.baz

现在我有一个下拉列表,其中包含以下列表项:

Now I have a drop down list that contains the following List Items:

var li1 = new ListItem() { Key = "foo" Value = "Actual Representation of Foo" }
var li2 = new ListItem() { Key = "bar" Value = "Actual Representation of Bar" }
var li3 = new ListItem() { Key = "baz" Value = "Actual Representation of Baz" }

有关完整起见:

dropDownListId.Items.Add(li1); dropDownListId.Items.Add(li2); dropDownListId.Items.Add(li3);

希望大家还是和我在一起。我想要做的是对的AutoPostBack就是以字符串foo和将其转换成Types.foo - 不使用开关(如枚举值从数据库中生成并可能改变)

Hope that everyone is still with me. What I want to do is to on the Autopostback is take the string "foo" and convert that to Types.foo - without using a switch (as the enumerated values are generated from a database and may change).

我希望是有道理?任何想法,甚至开始?

I hope that makes sense? Any idea where to even start?

推荐答案

当然:

Types t;
if(Enum.TryParse(yourString, out t)) // yourString is "foo", for example
{
    // use t
}
else
{
    // yourString does not contain a valid Types value
}

还有,需要一个布尔值,它允许你指定的情况下不敏感的过载:
http://msdn.microsoft.com/en-us/library/dd991317.aspx

Enum.TryParse 是.NET 4的新如果你被困在一个previous版本,你将不得不使用非类型安全< A HREF =htt​​p://msdn.microsoft.com/en-us/library/essfb559.aspx相对=nofollow> Enum.Parse 方法(罚全中转换失败的情况下的异常,而不是返回),像这样:

Enum.TryParse is new in .NET 4. If you're stuck on a previous version, you'll have to use the non-typesafe Enum.Parse method (which throws an exception in case of conversion failure, instead of returning false), like so:

try
{
    Types t = (Types)Enum.Parse(typeof(Types), yourString);
    // use t
}
catch(ArgumentException)
{
    // yourString does not contain a valid Types value
}

Enum.Parse 也有情况不敏感的过剩。

Enum.Parse also has an overload for case insensitiveness.

这篇关于从字符串获取一个枚举的场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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