简体   繁体   中英

Extension for IEnumerable<Enum>

I have the following:

var a = RoleEnum.Member;
var b = new List<RoleEnum> { RoleEnum.Member, RoleEnum.Editor };

string c = a.Humanize();
string d = b.Humanize();

While humanize is recognized in a.Humanize it is not recognized in b.Humanize.

The humanize extensions are as follows:

public static String Humanize(this Enum source) {
  return source.Attribute<DescriptionAttribute>().Description;      
}

public static String Humanize<T>(this IEnumerable<Enum> source) {
  return String.Join(", ", source.Cast<T>().Select(x => x.Attribute<DescriptionAttribute>().Description));
}

What am I missing here?

UPDATE 1

I changed the second extension to:

public static String Humanize<T>(this IEnumerable<T> source) where T : struct, IConvertible {
  return String.Join(", ", source.Cast<T>().Select(x => x.Attribute<DescriptionAttribute>().Description));
} // Humanize

But now I am having problems with the Attribute extension which is:

public static T Attribute<T>(this Enum value) where T : Attribute {
  MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
  if (info != null)
    return (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
  return null;
} // Attribute

Could someone help me in solving this?

One possible kick-it-in-the-teeth solution is to force it back to an object before casting to an Enum :

public static String Humanize<T>(this IEnumerable<T> source) where T : struct, IConvertible 
{
  return String.Join(", ", source.Cast<T>().Select(x => ((Enum)((object)x)).Attribute<DescriptionAttribute>().Description));
} 

This worked for me and printed the description for each Enum item in the list. I honestly hope somebody has a better solution though, because this has a pretty strong code smell!

Use IConvertible interface as type of argument for Attribute<T>() extension. Full code below

   public static class EnumExtensions
{
    public static String Humanize(this Enum source)
    {
        return source.Attribute<DescriptionAttribute>().Description;
    }

    public static String Humanize<T>(this IEnumerable<T> source) where T : struct, IConvertible
    {
        return String.Join(", ", source.Cast<T>().Select(x => x.Attribute<DescriptionAttribute>().Description));
    } // Humanize


    public static T Attribute<T>(this IConvertible value) where T : Attribute
    {
        MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
        if (info != null)
            return (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        return null;
    } // Attribute
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM