可能重复:
任何人都知道缺少枚举通用约束的好方法?
C#不允许对Enums 进行类型约束的原因是什么?我确信疯狂背后有一种方法,但我想明白为什么不可能.
以下是我希望能够做到的(理论上).
public static T GetEnum<T>(this string description) where T : Enum
{
...
}
Run Code Online (Sandbox Code Playgroud) 类似于C#中的Cast int to enum,但我的枚举是Generic Type参数.处理这个问题的最佳方法是什么?
例:
private T ConvertEnum<T>(int i) where T : struct, IConvertible
{
return (T)i;
}
Run Code Online (Sandbox Code Playgroud)
生成编译器错误 Cannot convert type 'int' to 'T'
完整代码如下,其中value可以包含int或null.
private int? TryParseInt(string value)
{
var i = 0;
if (!int.TryParse(value, out i))
{
return null;
}
return i;
}
private T? TryParseEnum<T>(string value) where T : struct, IConvertible
{
var i = TryParseInt(value);
if (!i.HasValue)
{
return null;
}
return (T)i.Value;
}
Run Code Online (Sandbox Code Playgroud)