Reflecting persistent properties / fields in .net

Possible duplicate:
Type.GetFields () - returns only public const fields.

I have a class that looks like this:

public class MyConstants { public const int ONE = 1; public const int TWO = 2; Type thisObject; public MyConstants() { thisObject = this.GetType(); } public void EnumerateConstants() { PropertyInfo[] thisObjectProperties = thisObject.GetProperties(BindingFlags.Public); foreach (PropertyInfo info in thisObjectProperties) { //need code to find out of the property is a constant } } } 

Basquely, he tries to repulse himself. I know how to reflect ONE and TWO fields. But how do you know if it is constant or not?

+7
reflection c # constants
source share
2 answers

This is because these are fields, not properties. Try:

  public void EnumerateConstants() { FieldInfo[] thisObjectProperties = thisObject.GetFields(); foreach (FieldInfo info in thisObjectProperties) { if (info.IsLiteral) { //Constant } } } 

Edit: DataDink to the right, it is smoother to use IsLiteral

+16
source share

FieldInfo objects actually have a ton of "IsSomething", logically on them:

 var m = new object(); foreach (var f in m.GetType().GetFields()) if (f.IsLiteral) { // stuff } 

This saves you a tiny amount of code by checking attributes anyway.

+5
source share

All Articles