3

I have a IReadOnlyList of instantiated classes. I would like to get all the public static fields that exists within each of these classes, and compare their names (the actual variable/field name as strings) to another group of strings (our case from an enumerator value name).

internal static string AttachBindablesToConfig(IReadOnlyList<Drawable> children)
{
    for (int i = 0; i < children.Count; i++)
    {
        var type = children[i].GetType(); // Get the class type
        var props = type.GetFields(); // Get fields within class
        return (props[0].GetValue(null)).ToString(); // Return a specific, testing purposes 
    }
    return "Failed";
}

// in another class

    Children = new Drawable[] { new Class1(), new Class2() };
    ..AttachBindablesToConfig(Children); // get value and display to screen

public class Class1
{
    // find these fields, and return their names (x, y, z) in a string format.
    public static someClass x;
    public static anotherClass y;
    public static int z;
}

This approach does not seem to be working. I would like an explanation as to why it doesn't work, and a clear answer which can hopefully fix this issue.

0

1 Answer 1

4

I would like to get all the public static fields that exists within each of these classes

I'm guessing you need to include the appropriate Binding Flags

BindingFlags Enumeration

Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.

var fieldNames = type.GetFields(BindingFlags.Public | BindingFlags.Static)
                               .Select(x => x.Name)
                               .ToList();

Note : I'm confused as to whether you want the name or the value, the above gets the list of names

If you want the value as well you could Select like this

.Select(x => x.Name + " = " + x.GetValue(children[i]))
2
  • I apologize for not wording my description accurately. I want the name of the variable, not its value. public static int x = 3; // I want x, not 3
    – Frontear
    Commented Mar 19, 2018 at 2:18
  • 1
    @Frontear i haven't tested this , however it should work, fingers crossed
    – TheGeneral
    Commented Mar 19, 2018 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.