Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to objects dynamically

Tags:

c#

reflection

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.

like image 833
John Tan Avatar asked Jan 29 '23 19:01

John Tan


1 Answers

You should use a dictionary of the Types <string, Obj> and then in the method do:

void CallObjectMethod(string name)
{
   Obj ObjFromDictionary = MyDictionary[name];
   ObjFromDictionary.CommonMethod();
}

you can of course call that directly without creating a temporary Obj ObjFromDictionary...

and you should validate that string parameter first...

like image 167
ΦXocę 웃 Пepeúpa ツ Avatar answered Feb 02 '23 11:02

ΦXocę 웃 Пepeúpa ツ