首页 > 编程语言 > 详细

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

时间:2015-01-30 01:25:34      阅读:320      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!