C#/.NET 枚举特性扩展——系统特性及自定义特性

版权声明:本文为博主原创文章,欢迎各位转载,但须注明出处 https://blog.csdn.net/qq_34202873/article/details/86064811

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

猜你喜欢

转载自blog.csdn.net/qq_34202873/article/details/86064811