Advertisement
Shirai

Reflection Get Const

Mar 31st, 2016
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ReflectionGetConst
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             var list = GetConstants< ClassTarget>();
  15.             foreach (var a in list)
  16.             {
  17.                 Console.WriteLine("{0} {1} {2} {3}", a.Attributes.ToString(), a.FieldType.FullName, a.Name, a.GetValue(null).ToString());
  18.             }
  19.             Console.ReadLine();
  20.         }
  21.         public static List<FieldInfo> GetConstants<T>()
  22.         {
  23.             var type = typeof (T);
  24.             FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public| BindingFlags.NonPublic| BindingFlags.Static | BindingFlags.FlattenHierarchy);
  25.  
  26.             return fieldInfos.Where(fi => fi.IsLiteral).ToList();
  27.         }
  28.     }
  29.  
  30.     public class ClassTarget
  31.     {
  32.         public const int a = 0;
  33.         public const int b = -10;
  34.         public const int c = 20;
  35.         public const int d = 3;
  36.         private const int e = 10;
  37.         private readonly int f = 4;
  38.         private int g = 12;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement