在 C# 中使用 enum 作为泛型类型参数
可能的重复:
C# 中的枚举类型约束
是否可以使用 enum
通过使用其包装类 Enum
将类型作为通用参数?
我有不同的枚举:
enum errors1 { E1, E3, E8 };
enum errors2 { E0, E2, E9 };
enum errors3 { E7, E4, E5 };
通过以下类声明,我认为我可以实现它:
public class MyErrors<T> where T : Enum
{
T enumeration;
public T getEnumeration()
{
return enumeration;
}
static void Main(string[] args)
{
Program<error1> p = new Program<error1>();
p.getEnumeration().E1 // this call does NOT work
}
但是,由于一般类型是 Enum
我只能访问 Enum
的成员和方法班级。那么是否可以按照我的意思来实现它,或者我应该使用什么其他方法?
Possible Duplicate:
Enum type constraints in C#
Is it possible to use enum
types as a generic paramter by using its wrapper class Enum
?
I have different enums:
enum errors1 { E1, E3, E8 };
enum errors2 { E0, E2, E9 };
enum errors3 { E7, E4, E5 };
With the following class declaration I thought I could achieve it:
public class MyErrors<T> where T : Enum
{
T enumeration;
public T getEnumeration()
{
return enumeration;
}
static void Main(string[] args)
{
Program<error1> p = new Program<error1>();
p.getEnumeration().E1 // this call does NOT work
}
However, since the general type is Enum
I can only access the member and methods of the Enum
class. So is it possible to implement it the way I meant to or what other approach should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不幸的是这是不可能的。您能做的最好的事情是使用
where T : struct, IComparable, IConvertible, IFormattable
(当然这是不一样的)。接口限制源自System.Enum
。
除此之外,您可以检查是否
typeof(T).IsEnum
,它可以在运行时检测问题并可能引发异常。但没有办法在编译时强制执行此限制。No, it's not possible unfortunately. The best you can do is use
where T : struct, IComparable, IConvertible, IFormattable
(which of course is not the same). The interface restrictions are derived from the implementation ofSystem.Enum
.Apart from that, you can check if
typeof(T).IsEnum
, which can detect the problem at runtime and presumably throw an exception. But there is no way to enforce this restriction at compile time.这在 C# 语言级别上是不可行的,但底层 CLR 支持它。您可以使用 Jon Skeet 的 Unconstrained Melody,它将生成的二进制文件转换为具有实际的枚举通用约束。
This is not doable at the language level in C#, but it's supported by the underlying CLR. You can use Jon Skeet's Unconstrained Melody, which will transform the generated binary to one with the actual enum generic constraint.