joh*_*hnc 1122 c# generics enums generic-constraints
我正在构建一个扩展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;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个Error Constraint不能是特殊类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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:(2015年2月16日)Julien Lebosquain最近在MSIL或F#下面发布了编译器强制类型安全通用解决方案,这非常值得一看,并且是一个upvote.如果解决方案在页面上向上冒泡,我将删除此编辑.
Viv*_*vek 961
由于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");
}
//...
}
Run Code Online (Sandbox Code Playgroud)
这仍然允许传递实现的值类型IConvertible
.但机会很少.
Chr*_*ens 601
以下代码段(来自dotnet示例)演示了它的用法:
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;
}
Run Code Online (Sandbox Code Playgroud)
请务必在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
}
}
Run Code Online (Sandbox Code Playgroud)
如果它是有效的C#,它会生成一个看起来像这样的函数:
T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
Run Code Online (Sandbox Code Playgroud)
然后使用以下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
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这意味着将这部分代码用MSIL而不是C#编写,唯一的好处是你能够通过约束这个方法System.Enum
.这也是一种无赖,因为它被编译成一个单独的程序集.但是,这并不意味着您必须以这种方式部署它.
删除行.assembly MyThing{}
并调用ilasm如下:
ilasm.exe /DLL /OUTPUT=MyThing.netmodule
Run Code Online (Sandbox Code Playgroud)
你得到一个netmodule而不是一个程序集.
不幸的是,VS2010(显然更早)不支持添加netmodule引用,这意味着在调试时必须将它保留在2个独立的程序集中.将它们作为程序集的一部分添加的唯一方法是使用/addmodule:{files}
命令行参数自行运行csc.exe .它在MSBuild脚本中不会太痛苦.当然,如果你是勇敢或愚蠢的,你可以每次手动运行csc.当多个程序集需要访问它时,它肯定会变得更加复杂.
所以,它可以在.Net中完成.值得付出额外的努力吗?嗯,好吧,我想我会让你决定那一个.
额外信用:事实证明enum
除了MSIL之外,至少还有一种其他.NET语言可以使用通用限制: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
Run Code Online (Sandbox Code Playgroud)
这个更易于维护,因为它是一个完全支持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);
Run Code Online (Sandbox Code Playgroud)
Jul*_*ain 197
从C#7.3开始(Visual Studio2017≥v15.7提供),此代码现在完全有效:
public static TEnum Parse<TEnum>(string value)
where TEnum : struct, Enum
{
...
}
Run Code Online (Sandbox Code Playgroud)
您可以通过滥用约束继承来获得真正的编译器强制枚举约束.以下代码同时指定a 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>
{
}
Run Code Online (Sandbox Code Playgroud)
用法:
EnumUtils.Parse<SomeEnum>("value");
Run Code Online (Sandbox Code Playgroud)
注意:这在C#5.0语言规范中有明确说明:
如果类型参数S依赖于类型参数T则:[...] S对于具有值类型约束而T具有引用类型约束是有效的.实际上,这将T限制为System.Object,System.ValueType,System.Enum和任何接口类型.
Yah*_*ous 30
编辑
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
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
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);
Run Code Online (Sandbox Code Playgroud)
旧
通过使用评论和"新"发展,我对Vivek答案的旧改进:
TEnum
的清晰度,为用户TryParse
处理ignoreCase
现有参数(在VS2010/.Net 4中引入)default
值(在VS2005/.Net 2中引入)defaultValue
和ignoreCase
导致:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Dis*_*nky 21
从 C# <=7.2 开始,现有答案是正确的。但是,有一个 C# 语言功能请求(与corefx功能请求相关联)允许以下操作;
public class MyGeneric<TEnum> where TEnum : System.Enum
{ }
Run Code Online (Sandbox Code Playgroud)
在撰写本文时,该功能在语言开发会议上处于“讨论中”。
编辑
编辑 2
这现在在 C# 7.3 中(发行说明)
样本;
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;
}
Run Code Online (Sandbox Code Playgroud)
Kar*_*arg 18
您可以为类定义静态构造函数,该构造函数将检查类型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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在parse方法中,您可以使用Enum.Parse(typeof(T),input,true)将字符串转换为枚举.最后一个真实参数用于忽略输入的大小写.
bau*_*arb 15
还应该考虑到,因为使用Enum约束的C#7.3的发布支持开箱即用而无需进行额外的检查和填充.
因此,如果您已将项目的语言版本更改为C#7.3,则以下代码将完美地运行:
private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
// Your code goes here...
}
Run Code Online (Sandbox Code Playgroud)
如果您不知道如何将语言版本更改为C#7.3,请参阅以下屏幕截图:
编辑1 - 必需的Visual Studio版本并考虑ReSharper
要使Visual Studio能够识别至少需要15.7版本的新语法.您可以在Microsoft的发行说明中找到它,请参阅Visual Studio 2017 15.7发行说明.感谢@MohamedElshawaf指出这个有效的问题.
请注意,在我的案例中,ReSharper 2018.1在编写此EDIT时尚不支持C#7.3.激活ReSharper会突出显示Enum约束,因为它告诉我不能使用'System.Array','System.Delegate','System.Enum','System.ValueType','object'作为类型参数约束.ReSharper建议快速修复删除方法类型参数T的'Enum'约束
但是,如果您在工具 - >选项 - > ReSharper Ultimate - >常规下暂时关闭ReSharper,您将看到语法完全正常,因为您使用VS 15.7或更高版本以及C#7.3或更高版本.
Biv*_*auc 11
我通过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);
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*oll 10
请注意,System.Enum
Parse()
&TryParse()
方法仍然具有where struct
约束而不是where Enum
,因此无法编译:
bool IsValid<TE>(string attempted) where TE : Enum
{
return Enum.TryParse(attempted, out TE _);
}
Run Code Online (Sandbox Code Playgroud)
但这将:
bool Ok<TE>(string attempted) where TE : struct,Enum
{
return Enum.TryParse(attempted, out var _)
}
Run Code Online (Sandbox Code Playgroud)
因此,where struct,Enum
可能比仅仅where Enum
我试着改进一下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
希望这是有帮助的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我确实有特定的要求,我需要使用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());
}
Run Code Online (Sandbox Code Playgroud)