如何限制一个泛型类型参数System.Enum [英] How to limit a generic type parameter to System.Enum

查看:309
本文介绍了如何限制一个泛型类型参数System.Enum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:
  <一href="http://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint">Anyone知道一个很好的解决方法缺乏一个枚举通用的限制呢?
  <一href="http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum">Create泛型方法约束T可枚举

Possible Duplicates:
Anyone know a good workaround for the lack of an enum generic constraint?
Create Generic method constraining T to an Enum

时可以限制泛型类型参数[我不知道这是正确的名称]到枚举

Is is possible to limit the generic type parameter [I don't know if that's the right name] to an Enum?

例如我怎么做这样的事?

For example how do I do something like this?

//VB.NET
Function GetValues(Of T As System.Enum)(ByVal value As T) As IEnumerable(Of T)
    Return [Enum].GetValues(value.GetType)
End Function

//C#
public IEnumerable<T> GetValues<T>(T value) where T : System.Enum
{
    return Enum.GetValues(value.GetType());
}


更新

我终于用乔恩斯基特的约束旋律用于这一目的。感谢大家的贡献。

I eventually used Jon Skeet's Unconstrained Melody for that purpose. Thanks to you all for your contributions.

推荐答案

不幸的是,你不能 - <一个href="http://connect.microsoft.com/VisualStudio/feedback/details/386194/allow-enum-as-generic-constraint-in-c">Microsoft关闭这个作为一个不会解决项。

Unfortunately, you cannot - Microsoft closed this one out as a won't fix item.

您可以把枚举的结构和使用,作为约束,而不是(我认为这是乔恩斯基特是如何做它的无约束的旋律?),但就是那种难看。

You can treat enums as structs and use that as the constraint instead (I think that was how Jon Skeet did it in Unconstrained Melody?) but that is kind of unsightly.

这篇关于如何限制一个泛型类型参数System.Enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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