1. 程式人生 > >C#/.NET 列舉特性擴充套件——系統特性及自定義特性

C#/.NET 列舉特性擴充套件——系統特性及自定義特性

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();
}