当前位置:   article > 正文

【Unity】自定义[Attribute]特性标记_unity attribute.getcustomattributes(type);

unity attribute.getcustomattributes(type);

继承Attribute,自定义特性类

  1. using System;
  2. public class HttpApiKey : Attribute
  3. {
  4. public HttpApiKey(string _httpApi)
  5. {
  6. httpApi = _httpApi;
  7. }
  8. public string httpApi;
  9. }

使用示例 

  1. public class HttpId
  2. {
  3. //示例,给id标记api
  4. [HttpApiKey("Register")]
  5. public const int registerId = 10001;
  6. [HttpApiKey("Login")]
  7. public const int loginId = 10002;
  8. public static void GetHttpApi()
  9. {
  10. //反射获取字段
  11. System.Reflection.FieldInfo[] fields = typeof(HttpId).GetFields();
  12. System.Type attType = typeof(HttpApiKey);
  13. for(int i = 0; i < fields.Length; i++)
  14. {
  15. if(fields[i].IsDefined(attType,false))
  16. {
  17. //获取id
  18. int httpId = (int)fields[i].GetValue(null);
  19. //获取api,读取字段的自定义Attribute
  20. object attribute = fields[i].GetCustomAttributes(typeof(HttpApiKey),false)[0];
  21. string httpApi = (attribute as HttpApiKey).httpApi;
  22. }
  23. }
  24. }
  25. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号