zoukankan      html  css  js  c++  java
  • 使用反射获取枚举的自定义属性Attribute

    自定义Attribue:ImgAttribute

     1 [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
     2 sealed class ImgAttribute : Attribute
     3 {
     4     readonly string imgUrl;
     5 
     6     public  ImgAttribute(string imgUrl)
     7     {
     8         this.imgUrl = imgUrl;
     9     }
    10     /// <summary>
    11     /// 图片地址
    12     /// </summary>
    13     public string ImgUrl
    14     {
    15         get { return imgUrl; }
    16     }
    17 }

    使用此属性的枚举:

     1 /// <summary>
     2 /// 交通方式
     3 /// </summary>
     4 public enum TransportType
     5 {
     6     [Img("/images/Airplane.jpg")]
     7     飞机=1,
     8     [Img("/images/bus.gif")]
     9     汽车=2,
    10     [Img("/images/Train.jpg")]
    11     火车=3,
    12     [Img("/images/Ship.jpg")]
    13     轮船=4,
    14     [Img("/images/Foot.jpg")]
    15     步行=5,
    16     [Img("/images/Bike.jpg")]
    17     自行车=6
    18 }

    使用反射获取属性值:

     1     /// <summary>
     2     /// 获取交通方式枚举的属性值(交通方式的图片地址)
     3     /// </summary>
     4     /// <param name="ttype"></param>
     5     /// <returns></returns>
     6     public static object getAttribute(TransportType ttype)
     7     {
     8         Type t = typeof(TransportType);
     9         FieldInfo[] info = t.GetFields();
    10         for (int i = 0; i < info.Length; i++)
    11         {
    12             if (info[i].Name == ttype.ToString())
    13             {
    14                 var att = info[i].GetCustomAttributes(false);
    15                 foreach (Attribute a in att)
    16                 {
    17                     if (a is ImgAttribute)
    18                     {
    19                         return ((ImgAttribute)a).ImgUrl;
    20                     }
    21                 }
    22                 break;
    23             }
    24         }
    25         return null;
    26     }


  • 相关阅读:
    solr学习四(关于性能的杂知识)
    solr学习三(测试类,含普通与ExtractingRequestHandler测试)
    solr学习二(ExtractingRequestHandler)
    solr学习一(一大堆的学习资料)
    ElasticSearch 5.0 简介
    solrcloud配置中文分词器ik
    SolrCloud6.3 单机、集群、内置jetty、tomcat搭建、对collection操作
    Solr6.2.0 + zookeeper 集群配置
    03: MySQL基本操作
    02: MySQL的安装与基本配置
  • 原文地址:https://www.cnblogs.com/jasonoiu/p/1795362.html
Copyright © 2011-2022 走看看