Reflection on Constants

A

Allan Rojas

Hi there, i'm new to reflection, i'm trying to retrieve a constant value,
but my code is not working:

....
public const int XXX = 5;

public void main()
{
System.Reflection.FieldInfo fi = this.GetType().GetField("XXX");
int temp = (int)fi.GetValue(this);
}
....

If i change the 'XXX' declaration to not-a-constant, the value is retrieved
successfully.
 
J

jennyq

Try out the following code snip.

namespace ConsoleApplication4

{

public class reflection

{

public const string mstr = "hello world!";

public reflection()

{

}

public static void Main()

{

System.Reflection.FieldInfo fi =
Type.GetType("ConsoleApplication4.reflection") .GetField("mstr");

string temp = (string)fi.GetValue(null);

Console.WriteLine("get string {0}", temp);

}

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top