如何约束泛型是枚举类型的? [英] How to constraint a generic to be of type enum?

查看:551
本文介绍了如何约束泛型是枚举类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

class Base<T>
{
 //Base members
}



我想要的通用T可为(使用约束如果可能的话)一个枚举。我怎样才能做到这在C#?

I want the generic T to be an enum (using constraints if possible). How can I do this in C#?

编辑:结果
使用由阿卡什Kava- -introduced代码合同也似乎是一个很好的方式。我设法得到它产生一个运行时错误,是没有用的。 这里的代码我试过了。它应该是可以生成编译时警告,但我无法得到它的工作。


Using code contracts -introduced by Akash Kava- also seems like a nice way. I managed to get it to produce a run time error which is useless. Here's the code I tried. It should be possible to generate a compile time warning but I can't get it to work.

推荐答案

这是在支持IL水平,但不是在C#。你可以看看不受约束的旋律通过乔恩斯基特写,让你实现这个。而这里的相应博客文章在那里,他解释细节。

This is supported at the IL level but not in C#. You may take a look at unconstrained melody written by Jon Skeet which allows you to achieve that. And here's the corresponding blog post where he explains in details.

这篇关于如何约束泛型是枚举类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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