C# 中 Enum.Parse 的通用版本 [英] Generic version of Enum.Parse in C#

查看:26
本文介绍了C# 中 Enum.Parse 的通用版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想知道为什么 C# 还没有实现 Generic Enum.Parse

I have regularly wondered why C# has not yet implemeted a Generic Enum.Parse

假设我有

enum MyEnum
{
   Value1,
   Value2
}

我希望从 XML 文件/数据库条目创建一个枚举.

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.

有什么想法吗?

推荐答案

它已经在 .NET 4 中实现了;) 看看 这里.

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屋!

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