题
我想创建一个接受 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() at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object [] parameters,CultureInfo culture,Boolean skipVisibilityChecks) 在System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object []参数,CultureInfo文化) 在System.Reflection.MethodBase.Invoke(Object obj,Object []参数)
编辑:上面的代码工作正常 - 我得到异常的原因是因为分析器导致了我的错误。谢谢大家的解决方案。
解决方案
以下是完整代码:
public enum Family
{
Brother,
Sister,
Father
}
public enum CarType
{
Volkswagen,
Ferrari,
BMW
}
static void Main(string[] args)
{
Console.WriteLine(GetEnumList<Family>());
Console.WriteLine(GetEnumList<Family>().First());
Console.ReadKey();
}
private static List<T> GetEnumList<T>()
{
T[] array = (T[])Enum.GetValues(typeof(T));
List<T> list = new List<T>(array);
return list;
}
其他提示
(Family[])Enum.GetValues(typeof(Family))
喜欢这个吗?
private static List<string> GetEnumList<T>()
{
return Enum.GetNames( typeof( T ) )
.Select(s => typeof(T).Name + "." + s).ToList();
}
不隶属于 StackOverflow