使用attribute + 扩展方法完成 enum中field的信息映射
  TEZNKK3IfmPf 2024年03月29日 66 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();
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年03月29日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   75   0   0 映射VLAN
  TEZNKK3IfmPf   2023年11月15日   39   0   0 映射
  TEZNKK3IfmPf   2023年11月13日   31   0   0 typescript映射
  TEZNKK3IfmPf   2023年11月13日   27   0   0 映射hibernate
  TEZNKK3IfmPf   2023年11月13日   189   0   0 MyBatis映射
TEZNKK3IfmPf