views:

85

answers:

2

I'm trying to iterate over the members of a static class and invoke all of the members that are fields. I get a MissingFieldException on the line where I attempt to invoke the member.

Something like this:

"Field 'NamespaceStuff.MyClass+MyStaticClass.A' not found."

public class MyClass {
    public MyClass() {
        Type type = typeof(MyStaticClass);
        MemberInfo[] members = type.GetMembers();

        foreach(MemberInfo member in members) {
            if (member.MemberType.ToString() == "Field")
            {
                // Error on this line
                int integer = type.InvokeMember(member.Name,
                                            BindingFlags.DeclaredOnly |
                                            BindingFlags.Public | 
                                            BindingFlags.Instance |
                                            BindingFlags.GetField,
                                            null, null, null);
            }
        }
    }
}

public static class MyStaticClass
{
    public static readonly int A = 1;
    public static readonly int B = 2;
    public static readonly int C = 3;
}

The array "members" looks something like this:

 [0]|{System.String ToString()}
 [1]|{Boolean Equals(System.Object)}
 [2]|{Int32 GetHashCode()}
 [3]|{System.Type GetType()}
 [4]|{Int32 A}
 [5]|{Int32 B}
 [6]|{Int32 C}

It blows up when it gets to index 4 in the foreach loop ('A' really is in there).

I passed in null for the second-to-last parameter in InvokeMember() because it's a static class, and there's nothing appropriate to pass in here. I'm guessing my problem is related to this, though.

Is what I'm trying to do possible? Maybe I'm going about it completely the wrong way. Also, please let me know if some of these BindingsFlags are superfluous.

+2  A: 

That's because A is static but you are using BindingFlags.Instance to call InvokeMember.

Pent Ploompuu
+4  A: 

If you know you only want public static fields on the class then you are probably better off using the following:

Type type = typeof (MyStaticClass);
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);

foreach (FieldInfo field in fields)
{
    var fieldValue = (int)field.GetValue(null);   
}

This will ensure that only the correct members are returned and you can get the field values.

Wallace Breza
lo.l you beat me too it
Rune FS
Perfect! This worked for me, thanks. Much easier to understand as well.I'm still trying to wrap my head around reflection.
Trevor