在 C# 中使用 enum 作为泛型类型参数

发布于 2024-11-16 15:10:52 字数 819 浏览 2 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毁我热情 2024-11-23 15:10:52

不,不幸的是这是不可能的。您能做的最好的事情是使用 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 of System.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.

温柔女人霸气范 2024-11-23 15:10:52

这在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文