首页 > 代码库 > 使用attribute + 扩展方法完成 enum中field的信息映射

使用attribute + 扩展方法完成 enum中field的信息映射

attribute可用来做信息映射,比起Dictionary或者Tuple,attribute显得更灵活,解耦,并可对应多种类型

以下是一个enum中的field的信息映射


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



2.准备一个extension 方法



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


    }



3. 在enum的field上应用特性


 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,
    }



4. 使用

job.JobAction.GetMetaData();


使用attribute + 扩展方法完成 enum中field的信息映射