C # - Iterate and call class members

I am trying to iterate over the elements of a static class and call all members that are fields. I get a MissingFieldException in the line where I am trying to call an element.

Something like that:

"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 elements of the array look 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 explodes when it hits index 4 in the foreach loop ("A" is really there).

I passed the null value for the second in the last parameter to InvokeMember (), because it is a static class, and there is nothing suitable here. I assume my problem is related to this.

Am I trying to do this? Maybe I will end this completely wrong. Also, please let me know if some of these BindingsFlags are redundant.

+4
source share
2 answers

If you know that a class requires public static fields , 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 ensures that only valid members are returned, and you can get the values ​​of the fields.

+12
source

This is because A is static , but you use BindingFlags.Instance to call InvokeMember .

+3
source

All Articles