나는이 하나를 가지고있는 경우 열거가 설명 속성을 얻을 수 있도록 IEnumerable 용 확장 메서드 <Enum>?
public enum MyEnum
{
[Description("Army of One")]
one,
[Description("Dynamic Duo")]
two,
[Description("Three Amigo's")]
three,
[Description("Fantastic Four")]
four,
[Description("The Jackson Five")]
five
}
내가 확장 방법을 썼습니다 ... 같은 다른 열거의 무리가 있습니다. 간단한만큼 바로 ...
public static string GetDescription(this Enum currentEnum)
{
var fi = currentEnum.GetType().GetField(currentEnum.ToString());
var da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
return da != null ? da.Description : currentEnum.ToString();
}
나는 아주 간단하게 이것을 사용할 수 있으며 예상대로 설명이나 ToString()를 반환 매력처럼 작동합니다.
그래도 문제가 있습니다. IEnumerable MyEnum, YourEnum 또는 SomeoneElsesEnum에서 호출 할 수있는 기능이 필요합니다. 그래서 나는 다음과 같은 확장을 간단히 썼습니다.
public static IEnumerable<string> GetDescriptions(this IEnumerable<Enum> enumCollection)
{
return enumCollection.ToList().ConvertAll(a => a.GetDescription());
}
이것은 작동하지 않습니다. 메서드로 잘 컴파일되지만 다음과 같은 오류가 발생합니다.
Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<MyEnum>' to System.Collections.Generic.IEnumerable<System.Enum>'
왜 그렇습니까? 나는이 작품을 만들 수 있습니까?
public static IEnumerable<string> GetDescriptions<T>(this List<T> myEnumList) where T : struct, IConvertible
public static string GetDescription<T>(this T currentEnum) where T : struct, IConvertible
누군가가 이것에 대한 더 나은 답변을, 또는 내가 열거 확장 할 수있는 이유에 대한 설명이 있어야합니다
나는이 시점에서 발견 한 유일한 대답은 다음과 같이 일반적인 T에 대한 확장 메서드를 작성하는 것입니다 Enum의 IEnumerable은 아니지만 ... 누구?