vendredi 11 août 2017

Refer to objects dynamically

Say I have 2 objects ObjA and ObjB. Assuming that they are from the same class with a method called CommonMethod(), I am looking for a method to do something like this:

void CallObjectMethod(string name)
{
    // where name could be 'A' or 'B'
    (Obj + name).CommonMethod();
}

instead of doing the long way:

void CallObjectMethod(string name)
{
    if(name == 'A')
        objA.CommonMethod();
    else if(name == 'B')
        objB.CommonMethod();
}

I understand this probably can be done through reflection, but not quite sure how to achieve this.





Aucun commentaire:

Enregistrer un commentaire