【C#高级语法特性锦集】
C#枚举特性扩展——系统特性及自定义特性
系统自带的特性
public static class EnumHelperExtensions
{
public static List<T> GetAllEnumMembers<T>()
{
if (!typeof(T).IsEnum)
{
throw new Exception("Only support Enum!");
}
List<T> list = new List<T>();
T t = default(T);
foreach (var m in Enum.GetValues(t.GetType()))
{
list.Add((T)m);
}
return list;
}
public static string GetDescription(this Enum source)
{
string description = null;
Type type = source.GetType();
FieldInfo[] fields = type.GetFields();
var attr = (DescriptionAttribute[])(fields.First(x => x.Name == source.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false));
if (attr != null && attr.Length != 0)
{
description = attr[0].Description;
}
return description;
}
}
public enum AxisTypes
{
[Description("X轴")]
AxisX,
AxisY,
AxisZ,
AxisW
}
//调用
private string GetAxisDescription(AxisTypes type)
{
//return type.GetDescription();
return AxisTypes.AxisX.GetDescription();
}
自定义扩展的特性
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class RemarkAttribute : Attribute
{
public RemarkAttribute(int remark)
{
this.Remark = remark;
}
public int Remark { get; private set; }
}
public static class RemarkExtend
{
/// <summary>
/// 扩展方法
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static int GetRemark(this Enum enumValue)
{
Type type = enumValue.GetType();
FieldInfo field = type.GetField(enumValue.ToString());
if (field.IsDefined(typeof(RemarkAttribute), true))
{
RemarkAttribute remarkAttribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute));
return remarkAttribute.Remark;
}
else
{
return Convert.ToInt32(enumValue);
}
}
}
public enum MotionTypes
{
[Remark(0)]
Continuous,
[Remark(1)]
Step
}
//调用
private string GetMotionRemark(MotionTypes type)
{
//return type.GetRemark();
return AxisTypes.Continuous.GetRemark();
}