如何获取枚举的所有值?
我想创建一个接受 Enum
类型的方法,并返回数组中的所有成员,如何创建这样的函数?
举例来说,我有这两个枚举:
public enum Family
{
Brother,
Sister,
Father
}
public enum CarType
{
Volkswagen,
Ferrari,
BMW
}
如何创建函数 GetEnumList
以便它为
- 第一个返回
{Family.Brother, Family.Sister, Family.Father}
案件。 {CarType.Volkswagen, CarType.Ferrari, CarType.BMW}
为第二种情况。
我尝试过:
private static List<T> GetEnumList<T>()
{
var enumList = Enum.GetValues(typeof(T))
.Cast<T>().ToList();
return enumList;
}
但我收到了 InvalidOperationException
:
System.InvalidOperationException:无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。 在 System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException() 在System.Reflection.RuntimeMethodInfo.Invoke(对象obj,BindingFlags invokeAttr,Binder活页夹,Object []参数,CultureInfo文化,布尔skipVisibilityChecks) 在System.Reflection.RuntimeMethodInfo.Invoke(对象obj,BindingFlags invokeAttr,Binder活页夹,Object []参数,CultureInfo文化) 在 System.Reflection.MethodBase.Invoke(Object obj, Object[] 参数)
编辑:上面的代码工作正常 - 我得到异常的原因是因为探查器导致了我的错误。 感谢大家提供的解决方案。
I want to create a method that takes in an Enum
type, and returns all it's members in an array, How to create such a function?
Take for example, I have these two enums:
public enum Family
{
Brother,
Sister,
Father
}
public enum CarType
{
Volkswagen,
Ferrari,
BMW
}
How to create a function GetEnumList
so that it returns
{Family.Brother, Family.Sister, Family.Father}
for the first case.{CarType.Volkswagen, CarType.Ferrari, CarType.BMW}
for the second case.
I tried :
private static List<T> GetEnumList<T>()
{
var enumList = Enum.GetValues(typeof(T))
.Cast<T>().ToList();
return enumList;
}
But I got an InvalidOperationException
:
System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
at System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException()
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
Edit: The above code is working fine-- the reason I got an exception was because profiler caused me the bug. Thank you all for your solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是完整的代码:
Here is the full code:
与其他答案相同,但针对现代 C# 进行了更新:
Same as the other answer but updated for modern C#:
像这样?
Like this?
从 .NET 5 开始,您可以执行以下操作:
Since .NET 5 you can do this: