Ale*_*fie 28 .net c# vb.net enums
是否可以将泛型类型参数[我不知道这是否是正确的名称]限制为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());
}
Run Code Online (Sandbox Code Playgroud)
更新
为了这个目的,我最终使用了Jon Skeet的Unconstrained Melody.感谢大家的贡献.
Che*_*hen 16
你不能.另一种解决方案是使用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());
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,你不能 - 微软关闭这个作为一个不会修复项目.
您可以将枚举视为结构并将其用作约束(我认为Jon Skeet是如何在无约束旋律中完成的?)但这有点难看.
Matt和Danny的答案都有一半的答案.这实际上应该可以满足您的需求:
public IEnumerable<T> GetValues<T>() where T : struct
{
if (!typeof(T).IsEnum) throw new InvalidOperationException("Generic type argument is not a System.Enum");
return Enum.GetValues(typeof(T)).OfType<T>();
}
Run Code Online (Sandbox Code Playgroud)
Danny回答的变化:
归档时间: |
|
查看次数: |
16861 次 |
最近记录: |