我正在构建一个扩展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 …Run Code Online (Sandbox Code Playgroud) 如果我有一个带有这样的struct约束的泛型接口:
public interface IStruct<T> where T : struct { }
Run Code Online (Sandbox Code Playgroud)
我可以提供枚举作为我的类型T,因为enum满足struct约束:
public class EnumIsAStruct : IStruct<DateTimeKind> { }
Run Code Online (Sandbox Code Playgroud)
C#7.3增加了一个Enum约束.以下代码以前是非法的,现在编译:
public class MCVE<T> : IStruct<T> where T : struct, Enum { }
Run Code Online (Sandbox Code Playgroud)
但令我惊讶的是,以下内容无法编译:
public class MCVE<T> : IStruct<T> where T : Enum { }
Run Code Online (Sandbox Code Playgroud)
......有错误
CS0453类型'T'必须是非可空值类型才能在泛型类型或方法'IStruct'中将其用作参数'T'
为什么是这样?我希望受限制的泛型类型Enum可用作类型参数,其中类型受约束struct但似乎不是这种情况 - 我必须将Enum约束更改为struct, Enum.我的期望是错的吗?
我想创建一个IRouteConstraint,它根据枚举的可能值过滤值.我试图为自己谷歌,但这并没有导致任何结果.
有任何想法吗?