문제

나는 Enum 배열에서 멤버를 모두 입력하고 반환합니다. 그러한 함수를 만드는 방법은 무엇입니까?

예를 들어, 나는이 두 열 열거가 있습니다.

public enum Family
{ 
   Brother,
   Sister,
   Father
}

public enum CarType
{ 
   Volkswagen,
   Ferrari,
   BMW
}

함수를 만드는 방법 GetEnumList 다시 돌아옵니다

  1. {Family.Brother, Family.Sister, Family.Father} 첫 번째 경우.
  2. {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 : GenericParameters를 포함하는 유형이나 방법에 대해서는 후기 바운드 작업을 수행 할 수 없습니다. system.reflection.runtimemethodinfo.thrownoinvokeexception ()에서 system.reflection.runtimemethodinfo.invoke (object obj, bindingflags invokeattr, binder binder, object [] 매개 변수, system.reflection.runtimemethodoke에서 oblean skipvisibilityChecks) , bindingflags invokeattr, binder binder, object [] 매개 변수, culture) system.reflection.methodbase.invoke (Object obj, Object [] 매개 변수)

편집 : 위의 코드는 제대로 작동합니다. 예외가 발생한 이유는 Profiler가 버그를 일으켰기 때문입니다. 솔루션에 감사드립니다.

도움이 되었습니까?

해결책

전체 코드는 다음과 같습니다.

    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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top