用枚举在C#泛型类型参数 [英] Using enum as generic type parameter in C#

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

问题描述

可能重复:结果
在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:结构,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天全站免登陆