class
EnumHelper<T, V>
where
T :
struct
where
V :
struct
{
private
static
IDictionary<T,
string
> enumAndDescriptionCache;
private
static
IDictionary<V,
string
> valueAndDescriptionCache;
static
EnumHelper()
{
Initialize();
}
/// <summary>
/// 初始化
/// </summary>
private
static
void
Initialize()
{
Type type =
typeof
(T);
if
(!type.IsEnum)
throw
new
ArgumentException(
"Generic type must be an enumeration"
);
string
[] enumNames = Enum.GetNames(type);
V[] enumValues = Enum.GetValues(type)
as
V[];
T[] enums = Enum.GetValues(type)
as
T[];
int
l = enumNames.Length;
enumAndDescriptionCache =
new
Dictionary<T,
string
>(l);
valueAndDescriptionCache =
new
Dictionary<V,
string
>(l);
EnumDescriptionAttribute tempAttr;
string
temp;
for
(
int
i = 0; i < l; i++)
{
tempAttr = GetDescriptionAttr(type.GetField(enumNames[i]));
temp = tempAttr ==
null
?
string
.Empty : tempAttr.Description;
enumAndDescriptionCache.Add(enums[i], temp);
valueAndDescriptionCache.Add(enumValues[i], temp);
}
}
/// <summary>
/// 获取枚举类型的描述信息,并加入到缓存中
/// </summary>
/// <param name="f"></param>
/// <param name="value"></param>
private
static
EnumDescriptionAttribute GetDescriptionAttr(FieldInfo f)
{
EnumDescriptionAttribute[] attrs = f.GetCustomAttributes(
typeof
(EnumDescriptionAttribute),
false
)
as
EnumDescriptionAttribute[];
if
(attrs !=
null
&& attrs.Length > 0)
{
return
attrs[0];
}
return
null
;
}
/// <summary>
/// 获取枚举类型的描述
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public
static
string
GetDescription(T value)
{
string
description =
null
;
if
(enumAndDescriptionCache.ContainsKey(value))
enumAndDescriptionCache.TryGetValue(value,
out
description);
return
description;
}
/// <summary>
/// 获取枚举类型的描述
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public
static
string
GetDescriptionByValue(V value)
{
string
description =
null
;
if
(valueAndDescriptionCache.ContainsKey(value))
valueAndDescriptionCache.TryGetValue(value,
out
description);
return
description;
}
/// <summary>
/// 获取枚举类型所有值及描述
/// </summary>
public
static
IEnumerable<KeyValuePair<T,
string
>> EnumDescriptions
{
get
{
foreach
(KeyValuePair<T,
string
> temp
in
enumAndDescriptionCache)
{
yield
return
temp;
}
}
}
/// <summary>
/// 获取枚举类型所有值及描述
/// </summary>
public
static
IEnumerable<KeyValuePair<V,
string
>> ValueDescriptions
{
get
{
foreach
(KeyValuePair<V,
string
> temp
in
valueAndDescriptionCache)
{
yield
return
temp;
}
}
}
}
请发表评论