在C#中使用枚举作为通用类型参数 [英] Using enum as generic type parameter in C#

查看:113
本文介绍了在C#中使用枚举作为通用类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C#中的枚举类型约束

Possible Duplicate:
Enum type constraints in C#

是否可以使用枚举通过使用其包装类枚举

Is it possible to use enum types as a generic paramter by using its wrapper class Enum?

我有不同的枚举:

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?

推荐答案

不,这是不可能的不幸。最好的是使用其中T:struct,IComparable,IConvertible,IFormattable (当然不一样)。接口限制来源于实施 系统。枚举

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 of System.Enum.

除此之外,您可以检查 typeof(T).IsEnum ,它可以在运行时检测问题,大概会抛出异常。但在编译时无法强制执行此限制。

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#中使用枚举作为通用类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆