samedi 24 août 2019

Getting a reference to all objects of a type in class in C#

Say I have a class with reference variables to some objects of type Foo. Say I now want to get a list of all of these variables dynamically, meaning if I add a new one that one will also be in the list.

I have tried using reflection, but I am not very experienced with it, so I think that is the right way but I'm not completely sure.

public class Foo() {
    public void Setup() {
        // Runs some code
    }
}

public class MyClass() {
    public Foo a;
    public Foo b;
    public Foo c;
    public Foo d;
    public Foo e;

    // Current constructor, does what I want but in a non-elegant way
    MyClass() {

        Foo[] foos= new Foo[] {
            a,
            b,
            c,
            d,
            e
        };
        foreach(Foo foo in foos) {
            foo.Setup();
        }
    }

    // The constructor I want, with GetAllMembersOfType<T>() dynamically
    // returning new objects as I add them to the class later
    MyClass() {

        Foo[] foos = GetAllMembersOfType<Foo>();
        foreach(Foo foo in foos) {
            foo.Setup();
        }
    }
}

How could I create a method like GetAllMembersOfType<T>()? Or at least a way to call Setup() on all member variables of type Foo?





Aucun commentaire:

Enregistrer un commentaire