如何将泛型类型参数限制为 System.Enum
可以将泛型类型参数 [我不知道这是否是正确的名称] 限制为 Enum
?
例如我该如何做这样的事情?
//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());
}
更新
我最终使用了 Jon Skeet 的 无约束的旋律就是为了这个目的。感谢大家的贡献。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。另一种解决方案是使用 struct 和运行时检查。
You can't. An alternative solution is using
struct
and run-time check.不幸的是,您不能 - Microsoft 已关闭这是一个无法修复的项目。
您可以将枚举视为结构并将其用作约束(我认为 Jon Skeet 在 不受约束的旋律?)但这有点难看。
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.
马特和丹尼的答案都只有一半。这实际上应该满足您的需求:
Danny 答案的更改:
Matt's and Danny's answers both have half the answer. This should actually get you what you need:
Changes from Danny's answer:
没有必要以这种方式使您的方法变得通用。
您可以仅使用 System.Enum 作为返回类型中的类型参数:
There is no need to make your method generic in this way.
You can just use the
System.Enum
as the type parameter in your return type: