我有以下几点:
var a = RoleEnum.Member;
var b = new List<RoleEnum> { RoleEnum.Member, RoleEnum.Editor };
string c = a.Humanize();
string d = b.Humanize();虽然人性化在a.Humanize中被识别,但在b.Humanize中却不被识别。
人性化扩展如下:
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));
}我在这里错过了什么?
更新1
我将第二个分机改为:
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 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有人能帮我解决这个问题吗?
发布于 2014-11-18 13:39:45
一个可能的解决方案是在转换到一个object之前强制它回到一个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));
} 这对我有效,并打印了清单中每个Enum项目的描述。老实说,我希望有人有一个更好的解决方案,因为这有很强的代码气味!
发布于 2014-11-18 14:10:36
使用IConvertible接口作为Attribute<T>()扩展的参数类型。下面是完整代码
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
}https://stackoverflow.com/questions/26994944
复制相似问题