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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With