提问
我正在构建一个扩展
Enum.Parse
概念的函数- 允许在未找到枚举值的情况下解析默认值
- 不区分大小写
所以我写了以下内容:
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
我得到的错误约束不能是特殊类
System.Enum
。很公平,但是有一个解决方法允许Generic Enum,或者我将不得不模仿
Parse
函数并将类型作为属性传递,这会迫使你的代码出现丑陋的拳击要求。编辑以下所有建议都非常感谢,谢谢。
已经解决了(我已离开循环以保持不区分大小写 - 我在解析XML时使用它)
public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
编辑:(2015年2月16日)Julien Lebosquain最近在MSIL或F#中发布了一个编译器强制类型安全通用解决方案,非常值得一看,并且是一个upvote。如果解决方案在页面上进一步冒出,我将删除此编辑。
最佳参考
由于
Enum
Type实现IConvertible
接口,更好的实现应该是这样的:public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
//...
}
这仍然允许传递实现
IConvertible
的值类型。但机会很少。其它参考1
C#7.3最终支持此功能!
以下代码段(来自dotnet示例)演示了它的用法:[64]
public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
请务必在C#项目中将语言版本设置为7.3版。
原始答案如下:
我迟到了游戏,但我把它作为一个挑战,看看它是如何完成的。它不可能在C#(或VB.NET,但向下滚动F#),但是可能的在MSIL中。我写了这个小东西
// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
如果它是有效的C#,它会生成 看起来像这样的函数:
T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
然后使用以下C#代码:
using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
不幸的是,这意味着将这部分代码用MSIL而不是C#编写,唯一的好处是你能够通过
System.Enum
来约束这个方法。它也有点无聊,因为它被编译成一个单独的程序集。但是,它并不意味着你必须以这种方式部署它。删除行
.assembly MyThing{}
并按如下方式调用ilasm:ilasm.exe /DLL /OUTPUT=MyThing.netmodule
你得到一个netmodule而不是一个程序集。
不幸的是,VS2010(显然更早)不支持添加netmodule引用,这意味着你在调试时必须将它留在2个独立的程序集中。将它们作为程序集的一部分添加的唯一方法是使用
/addmodule:{files}
命令行参数自行运行csc.exe。在MSBuild脚本中,它不会太痛苦。当然,如果你勇敢或愚蠢,你可以每次手动运行csc。当多个程序集需要访问它时,它肯定会变得更加复杂。所以,它可以在.Net中完成。是否值得付出额外的努力?嗯,好吧,我想我会让你决定那一个。
作为替代的F#解决方案
额外信用:事实证明除了MSIL之外,至少还有一种其他.NET语言可以对
enum
进行通用限制:F#。type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
这个更容易维护,因为它是一个着名的语言,完全支持Visual Studio IDE,但是你的解决方案仍然需要一个单独的项目。但是,它自然会产生相当不同的IL(代码是非常不同)它依赖于
FSharp.Core
库,就像任何其他外部库一样,它需要成为您的发行版的一部分。这里是你如何使用它(基本上与MSIL解决方案相同),并显示它在其他同义结构上正确失败:
// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
其它参考2
C#≥7.3
从C#7.3开始(Visual Studio2017≥v15.7提供),此代码现在完全有效:
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, Enum { ... }
C#≤7.2
您可以通过滥用约束继承来获得真正的编译器强制枚举约束。以下代码同时指定
class
和struct
约束:public abstract class EnumClassUtils<TClass>
where TClass : class
{
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, TClass
{
return (TEnum) Enum.Parse(typeof(TEnum), value);
}
}
public class EnumUtils : EnumClassUtils<Enum>
{
}
用法:
EnumUtils.Parse<SomeEnum>("value");
注意:这在C#5.0语言规范中有明确说明:
如果类型参数S取决于类型参数T,则:
[[...]]它有效
S具有值类型约束,T具有引用类型
约束。实际上,这将T限制为System.Object类型,
System.ValueType,System.Enum和任何接口类型。
其它参考3
修改
Julien Lebosquain现在已经很好地回答了这个问题。
我还想用
ignoreCase
,defaultValue
和可选论点扩展他的答案,同时加上TryParse
和ParseOrDefault
。public abstract class ConstrainedEnumParser<TClass> where TClass : class
// value type constraint S ("TEnum") depends on reference type T ("TClass") [and on struct]
{
// internal constructor, to prevent this class from being inherited outside this code
internal ConstrainedEnumParser() {}
// Parse using pragmatic/adhoc hard cast:
// - struct + class = enum
// - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils
public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass
{
return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);
}
public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
{
var didParse = Enum.TryParse(value, ignoreCase, out result);
if (didParse == false)
{
result = defaultValue;
}
return didParse;
}
public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
{
if (string.IsNullOrEmpty(value)) { return defaultValue; }
TEnum result;
if (Enum.TryParse(value, ignoreCase, out result)) { return result; }
return defaultValue;
}
}
public class EnumUtils: ConstrainedEnumParser<System.Enum>
// reference type constraint to any <System.Enum>
{
// call to parse will then contain constraint to specific <System.Enum>-class
}
用法示例:
WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>("monday", ignoreCase:true);
WeekDay parsedDayOrDefault;
bool didParse = EnumUtils.TryParse<WeekDay>("clubs", out parsedDayOrDefault, ignoreCase:true);
parsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>("friday", ignoreCase:true, defaultValue:WeekDay.Sunday);
旧
通过使用评论和新发展,我对Vivek答案的旧改进:
- 使用
TEnum
来明确用户 - 为附加约束检查添加更多接口约束
- 让
TryParse
使用现有参数处理ignoreCase
(在VS2010/.Net 4中介绍) - 可选地使用通用
default
值(在VS2005/.Net 2中引入) - 对
defaultValue
和ignoreCase
使用默认值的可选参数(在VS2010/.Net 4中引入)
导致:[67] [68] [69]
public static class EnumUtils
{
public static TEnum ParseEnum<TEnum>(this string value,
bool ignoreCase = true,
TEnum defaultValue = default(TEnum))
where TEnum : struct, IComparable, IFormattable, IConvertible
{
if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); }
if (string.IsNullOrEmpty(value)) { return defaultValue; }
TEnum lResult;
if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }
return defaultValue;
}
}
其它参考4
您可以为类定义静态构造函数,该构造函数将检查类型T是否为枚举,如果不是则抛出异常。这是Jeffery Richter在他的书CLR中通过C#提到的方法。
internal sealed class GenericTypeThatRequiresAnEnum<T> {
static GenericTypeThatRequiresAnEnum() {
if (!typeof(T).IsEnum) {
throw new ArgumentException("T must be an enumerated type");
}
}
}
然后在parse方法中,您可以使用Enum.Parse(typeof(T),input,true)将字符串转换为枚举。最后一个真实参数用于忽略输入的大小写。
其它参考5
我通过dimarzionist修改了样本。此版本仅适用于Enums,不允许结构通过。
public static T ParseEnum<T>(string enumString)
where T : struct // enum
{
if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
throw new Exception("Type given must be an Enum");
try
{
return (T)Enum.Parse(typeof(T), enumString, true);
}
catch (Exception ex)
{
return default(T);
}
}
其它参考6
我试着改进一下代码:
public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
return defaultValue;
}
其它参考7
还应该考虑到,因为使用Enum约束的C#7.3的发布支持开箱即用而无需进行额外的检查和填充。
因此,如果您已经将项目的语言版本更改为C#7.3,那么以下代码将完美地运行:
private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
// Your code goes here...
}
如果您不知道如何将语言版本更改为C#7.3,请参阅以下屏幕截图:
编辑1 - 必需的Visual Studio版本并考虑ReSharper
要使Visual Studio能够识别至少需要15.7版本的新语法。您可以在Microsoft的发行说明中找到,请参阅Visual Studio 2017 15.7发行说明。感谢@MohamedElshawaf指出这个有效的问题。[71]
请注意,在我的案例中,ReSharper 2018.1在编写此EDIT时尚不支持C#7.3。激活ReSharper后,它突出显示Enum约束,因为错误告诉我不能使用System.Array,System.Delegate,System.Enum,System.ValueType,object作为类型参数约束的。
ReSharper建议快速修复删除方法类型参数T的
但是,如果您在工具 - >选项 - > ReSharper Ultimate - >常规下暂时关闭ReSharper,您会看到语法完全没问题,因为您使用VS 15.7或更高版本以及C#7.3或更高版本。
其它参考8
我确实有特定的要求,我需要使用enum与enum值相关联的文本。例如,当我使用enum指定错误类型时,它需要描述错误详细信息。
public static class XmlEnumExtension
{
public static string ReadXmlEnumAttribute(this Enum value)
{
if (value == null) throw new ArgumentNullException("value");
var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);
return attribs.Length > 0 ? attribs[0].Name : value.ToString();
}
public static T ParseXmlEnumAttribute<T>(this string str)
{
foreach (T item in Enum.GetValues(typeof(T)))
{
var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);
if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;
}
return (T)Enum.Parse(typeof(T), str, true);
}
}
public enum MyEnum
{
[XmlEnum("First Value")]
One,
[XmlEnum("Second Value")]
Two,
Three
}
static void Main()
{
// Parsing from XmlEnum attribute
var str = "Second Value";
var me = str.ParseXmlEnumAttribute<MyEnum>();
System.Console.WriteLine(me.ReadXmlEnumAttribute());
// Parsing without XmlEnum
str = "Three";
me = str.ParseXmlEnumAttribute<MyEnum>();
System.Console.WriteLine(me.ReadXmlEnumAttribute());
me = MyEnum.One;
System.Console.WriteLine(me.ReadXmlEnumAttribute());
}
其它参考9
希望这有用:
public static TValue ParseEnum<TValue>(string value, TValue defaultValue)
where TValue : struct // enum
{
try
{
if (String.IsNullOrEmpty(value))
return defaultValue;
return (TValue)Enum.Parse(typeof (TValue), value);
}
catch(Exception ex)
{
return defaultValue;
}
}
其它参考10
有趣的是,显然这在其他语言中是可行的(Managed C ++,IL直接)。 [72]
去引用:
...两个约束实际上产生有效的IL,如果用另一种语言编写,也可以被C#使用(您可以在托管C ++或IL中声明这些约束)。
谁知道
其它参考11
这是我的看法。结合答案和MSDN
public static TEnum ParseToEnum<TEnum>(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an Enum type");
try
{
var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);
return enumValue;
}
catch (Exception)
{
throw new ArgumentException(string.Format("{0} is not a member of the {1} enumeration.", text, typeof(TEnum).Name));
}
}
MSDN来源[73]
其它参考12
从C#<=7.2开始,现有答案都是正确的。但是,有一个C#语言功能请求(与corefx功能请求绑定)允许以下内容; [74] [75]
public class MyGeneric<TEnum> where TEnum : System.Enum
{ }
在撰写本文时,该功能在语言发展会议上进行了讨论。
修改
根据nawfal的信息,这是在C#7.3中引入的。 [77]
其它参考13
我总是喜欢这个(你可以根据需要修改):
public static IEnumerable<TEnum> GetEnumValues()
{
Type enumType = typeof(TEnum);
if(!enumType.IsEnum)
throw new ArgumentException("Type argument must be Enum type");
Array enumValues = Enum.GetValues(enumType);
return enumValues.Cast<TEnum>();
}
其它参考14
我喜欢使用IL的Christopher Currens解决方案,但对于那些不想处理将MSIL包含在构建过程中的棘手业务的人,我在C#中编写了类似的功能。
请注意,虽然你不能像
where T : Enum
这样使用通用限制,因为Enum是特殊类型。因此我必须检查给定的泛型类型是否真的是枚举。我的功能是:
public static T GetEnumFromString<T>(string strValue, T defaultValue)
{
// Check if it realy enum at runtime
if (!typeof(T).IsEnum)
throw new ArgumentException("Method GetEnumFromString can be used with enums only");
if (!string.IsNullOrEmpty(strValue))
{
IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();
while (enumerator.MoveNext())
{
T temp = (T)enumerator.Current;
if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))
return temp;
}
}
return defaultValue;
}
其它参考15
我已将Vivek的解决方案封装到您可以重用的实用程序类中。请注意,您仍应在类型上定义类型约束where T:struct,IConvertible。
using System;
internal static class EnumEnforcer
{
/// <summary>
/// Makes sure that generic input parameter is of an enumerated type.
/// </summary>
/// <typeparam name="T">Type that should be checked.</typeparam>
/// <param name="typeParameterName">Name of the type parameter.</param>
/// <param name="methodName">Name of the method which accepted the parameter.</param>
public static void EnforceIsEnum<T>(string typeParameterName, string methodName)
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
string message = string.Format(
"Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.",
typeParameterName,
methodName);
throw new ArgumentException(message);
}
}
/// <summary>
/// Makes sure that generic input parameter is of an enumerated type.
/// </summary>
/// <typeparam name="T">Type that should be checked.</typeparam>
/// <param name="typeParameterName">Name of the type parameter.</param>
/// <param name="methodName">Name of the method which accepted the parameter.</param>
/// <param name="inputParameterName">Name of the input parameter of this page.</param>
public static void EnforceIsEnum<T>(string typeParameterName, string methodName, string inputParameterName)
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
string message = string.Format(
"Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.",
typeParameterName,
methodName,
inputParameterName);
throw new ArgumentException(message);
}
}
/// <summary>
/// Makes sure that generic input parameter is of an enumerated type.
/// </summary>
/// <typeparam name="T">Type that should be checked.</typeparam>
/// <param name="exceptionMessage">Message to show in case T is not an enum.</param>
public static void EnforceIsEnum<T>(string exceptionMessage)
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException(exceptionMessage);
}
}
}
其它参考16
我创建了一个扩展方法
to get integer value from enum
看一下方法实现
public static int ToInt<T>(this T soure) where T : IConvertible//enum
{
if (typeof(T).IsEnum)
{
return (int) (IConvertible)soure;// the tricky part
}
//else
// throw new ArgumentException("T must be an enumerated type");
return soure.ToInt32(CultureInfo.CurrentCulture);
}
这是用法
MemberStatusEnum.Activated.ToInt()// using extension Method
(int) MemberStatusEnum.Activated //the ordinary way
其它参考17
如之前的其他答案所述;虽然这不能用源代码表示,但它实际上可以在IL Level上完成。
@Christopher Currens的答案显示了IL如何做到这一点。
使用Fodys Add-In ExtraConstraints.Fody有一个非常简单的方法,完成构建工具,实现这一点。只需将他们的nuget包(
Fody
,ExtraConstraints.Fody
)添加到您的项目并添加约束如下(摘自ExtraConstraints自述文件):[79] [80]public void MethodWithEnumConstraint<[EnumConstraint] T>() {...}
public void MethodWithTypeEnumConstraint<[EnumConstraint(typeof(ConsoleColor))] T>() {...}
并且Fody将为存在的约束添加必要的IL。
另请注意约束代表的附加功能:
public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
{...}
public void MethodWithTypeDelegateConstraint<[DelegateConstraint(typeof(Func<int>))] T> ()
{...}
关于Enums,您可能还需要注意非常有趣的Enums.NET。[81]
其它参考18
如果之后可以使用直接强制转换,我猜你可以在你的方法中使用
System.Enum
基类,只要有必要。你只需要仔细替换类型参数。所以方法实现如下:public static class EnumUtils
{
public static Enum GetEnumFromString(string value, Enum defaultValue)
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (Enum item in Enum.GetValues(defaultValue.GetType()))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
然后你就可以使用它:
var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);
其它参考19
在java中,你会用...
SomeClass<T extends enum> {
}
很简单,那个。