C#中Enum.Parse的通用版本 [英] Generic version of Enum.Parse in C#
本文介绍了C#中Enum.Parse的通用版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常想知道为什么C#还没有实现泛型Enum.Parse
可以说我有
< pre class =lang-cs prettyprint-override> enum MyEnum
{
Value1,
Value2
}
从XML文件/数据库条目我想创建一个枚举。
MyEnum val =(MyEnum)Enum.Parse(typeof(MyEnum),value1,true);
它可能不是像
那样实现的 MyEnum cal = Enum.Parse< MyEnum>(value1);
这可能看起来像一个小问题,但它似乎是一个被忽视的问题。
有什么想法?
解决方案
它已经在.NET 4中实现;看此处。
MyEnum cal;
if(!Enum.TryParse< MyEnum>(value1,out cal))
抛出新的异常(value1不是枚举MyEnum的有效成员);
另外讨论这里包含一些有趣的观点。
I have regularly wondered why C# has not yet implemeted a Generic Enum.Parse
Lets say I have
enum MyEnum
{
Value1,
Value2
}
And from an XML file/DB entry I wish to to create an Enum.
MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), "value1", true);
Could it not have been implemented as something like
MyEnum cal = Enum.Parse<MyEnum>("value1");
This might seem like a small issue, but it seems like an overlooked one.
Any thoughts?
解决方案
It is already implemented in .NET 4 ;) Take a look here.
MyEnum cal;
if (!Enum.TryParse<MyEnum>("value1", out cal))
throw new Exception("value1 is not valid member of enumeration MyEnum");
Also the discussion here contains some interesting points.
这篇关于C#中Enum.Parse的通用版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文