Guest User

Untitled

a guest
Jul 16th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6.  
  7. namespace Enumに柔軟な拡張を追加する試み {
  8. class Program {
  9. enum tesyEnum {
  10. [Obsolete]
  11. a,
  12. [RelatedLiteral("hoge")]
  13. b,
  14. }
  15.  
  16. enum tesyEnum2 {
  17. [RelatedLiteral(2)]
  18. c,
  19. [RelatedLiteral(0.5)]
  20. d
  21. }
  22.  
  23. static void Main(string[] args) {
  24.  
  25. //Console.WriteLine(tesyEnum.a.GetRelatedLiteral()); RelatedLiteral属性つけてないと例外発生
  26. Console.WriteLine(tesyEnum.b.GetRelatedLiteral());
  27. Console.WriteLine(tesyEnum2.c.GetRelatedLiteral());
  28. Console.WriteLine(tesyEnum2.d.GetRelatedLiteral());
  29. Console.Read();
  30. }
  31. }
  32.  
  33.  
  34. [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
  35. public class RelatedLiteralAttribute : Attribute {
  36. public RelatedLiteralAttribute(object value) {
  37. Value = value;
  38. }
  39. public dynamic Value { get; private set; }
  40. }
  41.  
  42.  
  43. /// <summary>
  44. /// enum拡張メソッド用クラス
  45. /// </summary>
  46. public static class EnumExtension {
  47. /// <summary>
  48. /// RelatedLiteral属性に指定したリテラルを取得します。
  49. /// </summary>
  50. /// <param name="myself"></param>
  51. /// <returns></returns>
  52. public static dynamic GetRelatedLiteral(this Enum myself) {
  53. Type type = myself.GetType();
  54. string name = Enum.GetName(type, myself);
  55. try {
  56. FieldInfo fi = type.GetField(name);
  57. var items = (RelatedLiteralAttribute[])fi.GetCustomAttributes(typeof(RelatedLiteralAttribute), false);
  58. return items[0].Value;
  59. }
  60. catch (IndexOutOfRangeException e) {
  61. throw new CustomAttributeFormatException(type.Name + " の " + name + " 要素にEnumAttr属性が指定されていません。");
  62. }
  63. }
  64. }
  65. }
Add Comment
Please, Sign In to add comment