Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of fields from a class that is instantiated within a list, and compare them

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.

like image 527
Frontear Avatar asked Jan 02 '26 00:01

Frontear


1 Answers

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]))
like image 68
TheGeneral Avatar answered Jan 04 '26 01:01

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!