[英]Extension for IEnumerable<Enum>
我有以下几点:
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
有人可以帮我解决这个问题吗?
一种可行的解决方案是在强制转换为Enum
之前将其强制返回object
:
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项目的描述。 老实说,我希望有人能有更好的解决方案,因为这有很强的代码味道!
使用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.