c# - 如何将泛型类型参数限制为 System.Enum

标签 c# .net vb.net enums

<分区>

Possible Duplicates:
Anyone know a good workaround for the lack of an enum generic constraint?
Create Generic method constraining T to an 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 的 Unconstrained Melody为了这个目的。感谢大家的贡献。

最佳答案

你不能。另一种解决方案是使用 struct 和运行时检查。

public IEnumerable<T> GetValues<T>(T value) where T : struct
{  
    if (!typeof(T).IsEnum) throw new NotSupportedException();
    return (IEnumerable<T>)Enum.GetValues(value.GetType()); 
} 

关于c# - 如何将泛型类型参数限制为 System.Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067724/

相关文章:

c# - 计算带锁和不带锁的线程 (c#)

javascript - 如何在javascript中检查日期大于或小于的条件?

c# - 从 ElementTree 的根传递元素作为 CommandParameter

.net - ListView跳转或者不收缩

c# - 在 .NET 中验证 Mandrill 入站 Webhook 请求

vb.net - 根据光标所在位置将文本添加到文本框

vb.net - 使用Visual Studio的ArcGIS 10.2调试

c# - 如何将CSS类设置为数据列表?

c# - 在存储帐户之间复制 blob

c# - 如何在 c# 中为 Microsoft.office.interop.word 实现后期绑定(bind)?