从字符串中获取枚举字段
这有点奇怪。请原谅下面的半伪代码。我有一个枚举值列表。比如说,像这样:
public enum Types
{
foo = 1,
bar = 2,
baz = 3
}
恭敬地,在代码中将变成:
Types.foo
Types.bar
Types.baz
现在我有一个包含以下列表项的下拉列表:
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 - 不使用开关(因为枚举值是从数据库生成的并且可能会更改)。
我希望这是有道理的?知道从哪里开始吗?
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
}
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" }
for the sake of completeness:
dropDownListId.Items.Add(li1); dropDownListId.Items.Add(li2); dropDownListId.Items.Add(li3);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然:
还有一个重载需要一个布尔值,允许您指定不区分大小写:
http://msdn.microsoft.com/en-us/library/dd991317.aspx
Enum.TryParse
是 .NET 4 中的新功能。如果您坚持使用以前的版本,则必须使用非类型安全的Enum.Parse
方法(在转换失败的情况下,而不是返回false
),如下所示:Enum.Parse
还具有不区分大小写的重载。Sure:
There's also an overload that takes a boolean that allows you to specify case insensitiveness:
http://msdn.microsoft.com/en-us/library/dd991317.aspx
Enum.TryParse
is new in .NET 4. If you're stuck on a previous version, you'll have to use the non-typesafeEnum.Parse
method (which throws an exception in case of conversion failure, instead of returningfalse
), like so:Enum.Parse
also has an overload for case insensitiveness.那么,您想要:
Enum.Parse(typeof(Types), postbackValue)
或者我错过了什么?
So, you want:
Enum.Parse(typeof(Types), postbackValue)
or did I miss something?
如果我理解正确,您可以执行以下操作:
请参阅:http://msdn.microsoft。 com/en-us/library/essfb559.aspx
If I understood correctly, you can do:
See: http://msdn.microsoft.com/en-us/library/essfb559.aspx