码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-01-30 01:27:45      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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的信息映射

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/43289471

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!