标签:
attribute可用来做信息映射,比起Dictionary或者Tuple,attribute显得更灵活,解耦,并可对应多种类型1. 创建field attribute
[AttributeUsage(AttributeTargets.Field)] public class JobActionMetadatAttribute : Attribute { public JobActionUIType UIType { get; private set; } public string Label { get; private set; } public JobActionMetadatAttribute(JobActionUIType uiType, string label) { UIType = uiType; Label = label; } }
public static class JobActionExtenssion { public static JobActionMetadata GetMetaData(this JobAction jobAction) { var attr = Attribute.GetCustomAttribute(jobAction.GetType().GetMember(jobAction.ToString())[0], typeof(JobActionMetadatAttribute)); if (attr != null) { var props = attr.GetType().GetProperties(); JobActionUIType uiType; var uiTypeObj = props.FirstOrDefault(p => p.PropertyType == typeof(JobActionUIType)); if (uiTypeObj == null) { throw new InvalidDataException(string.Format("Failed to find JobActionUIType Property in JobActionMetadataAttribute")); } var uiTypeStr = uiTypeObj.GetValue(attr, null).ToString(); if (!Enum.TryParse(uiTypeStr, true, out uiType)) { throw new InvalidEnumArgumentException(string.Format("Enum Parsing failed. string : {0}", uiTypeStr)); } var label = props.First(p => p.Name == "Label").GetValue(attr, null).ToString(); return new JobActionMetadata(jobAction, uiType, label, ""); } throw new InvalidDataException(string.Format("Failed to find JobActionMetadatAttribute for Action : {0}", jobAction)); } }
public enum JobAction { [JobActionMetadatAttribute(JobActionUIType.Success, "Paypal Payment")] MakePayPalSimplePayment = 0, [JobActionMetadatAttribute(JobActionUIType.Success, "Pay by Free Pass")] MakeFreePassPayment = 1, [JobActionMetadatAttribute(JobActionUIType.Success, "Pay by Company Credit")] MakeCompanyCreditPayment = 2, }
job.JobAction.GetMetaData();
使用attribute + 扩展方法完成 enum中field的信息映射
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/43289471