如何将通用类型参数限制为System.Enum [英] How to limit a generic type parameter to System.Enum

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

问题描述


可能的重复:


创建将T限制为枚举的通用方法


有可能限制通用类型参数[我不知道这是否是正确的名称]到枚举



例如,我该如何做这样的事?

  // VB.NET 
函数GetValues(Of T As System.Enum)(ByVal value As T)As IEnumerable(Of T)
返回[枚举]。 GetValues(value.GetType)
结束函数

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






更新



我最终使用了Jon Skeet的无约束旋律为此目的。感谢你们的贡献。

解决方案

不幸的是,你不能 - Microsoft关闭这个,因为不会修复项目。 p>

您可以将枚举视为结构体,并将其用作约束(我认为这是Jon Skeet在 Uncontstrained Melody ?)但是那种不好看的。


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());
}


Update

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

解决方案

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天全站免登陆