…meie igapäevast IT’d anna meile igapäev…

2012-03-06

Get all constant values of a class using reflection

Filed under: Programmeerimine — Sander @ 18:38:23
Tags: , ,
  1. /// <summary>
  2. /// Return all the values of constants of the specified type
  3. /// </summary>
  4. /// <typeparam name="T">What type of constants to return</typeparam>
  5. /// <param name="type">Type to examine</param>
  6. /// <returns>List of constant values</returns>
  7. public static List<T> GetConstantValues<T>(Type type)
  8. {
  9.     FieldInfo[] fields = type.GetFields(BindingFlags.Public
  10.         | BindingFlags.Static
  11.         | BindingFlags.FlattenHierarchy);
  12.  
  13.     return (fields.Where(fieldInfo => fieldInfo.IsLiteral
  14.         && !fieldInfo.IsInitOnly
  15.         && fieldInfo.FieldType == typeof(T)).Select(fi => (T)fi.GetRawConstantValue())).ToList();
  16. }

Above is a simple generic method to get all constants of a specific type of a class. I.e. to get all string constants, use:

var allStringConstants = GetConstantValues<string>(typeof(myClass));

To get all int values:

var allIntConstants = GetConstantValues<int>(typeof(myClass));

and so forth.

The inspiration for this method came from http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx

Lisa kommentaar »

Kommentaare veel pole.

RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Muuda )

Twitter picture

You are commenting using your Twitter account. Log Out / Muuda )

Facebook photo

You are commenting using your Facebook account. Log Out / Muuda )

Google+ photo

You are commenting using your Google+ account. Log Out / Muuda )

Connecting to %s

Create a free website or blog at WordPress.com.