I got things working just after I sent this email.  Here's the solution for
anyone interested:

        FieldInfo[] fields = typeof(Ids).GetFields(
                BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo field in fields)
        {

                // Now using GetValue()
                IdDef idDef = (IdDef) field.GetValue(null);
                Console.WriteLine("id:{0}, hasA:{1} hasB:{2}",
                        idDef.Id, idDef.HasA, idDef.HasB);
        }

FieldInfo.GetValue() did the trick.

Thanks, Ryan





-----Original Message-----
From: Ryan Parlee [mailto:[EMAIL PROTECTED]
Sent: Thursday, August 03, 2006 11:42 AM
To: 'Discussion of advanced .NET topics.'
Subject: Using reflection to enumerate static fields

I have the following classes:

public class IdDef
{
        public IdDef(int id, bool hasA, bool hasB)
        {
                this.Id =id; this.HasA = hasA; this.HasB = hasB;
        }
        public int Id;
        public bool HasA;
        public bool HasB;
}

public class Ids
{
        private Ids() {}

        public static IdDef IdA = new IdDef(1, true, true);
        public static IdDef IdB = new IdDef(2, true, false);
        public static IdDef IdC = new IdDef(3, false, true);
}


I need to use reflection to enumerate the "Ids" class. I started with the
following code which seems like it should work if I could figure out how to
marshal the field handle into and IdDef object.  Am I just missing a simple
marshalling step or am I way off?


        FieldInfo[] fields = typeof(Ids).GetFields(
                BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo field in fields)
        {

                // this doesn't work!
                IdDef idDef = (IdDef) Field.FieldHandle;

                Console.WriteLine("id:{0}, hasA:{1} hasB:{2}",
                        idDef.Id, idDef.HasA, idDef.HasB);
        }

Thanks, Ryan

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to