Dynamically access objects

Let's say I have 2 objects ObjAand ObjB. Assuming they are from the same class with a method called CommonMethod(), I am looking for a way to do something like this:

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

instead of a long way:

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

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

+4
source share
2 answers

Assuming that ObjAboth ObjBhave a class SomeClassand are fields (member variables) this, you can use the following. If the caller supplies the wrong suffix (for example, not โ€œAโ€, not โ€œBโ€), the method will throw an exception, of course.

class Example
{
    private SomeClass ObjA;
    private SomeClass ObjB;

    void CallObjectMethod(string suffix)
    {
        string name = "Obj" + suffix;
        var fieldInfo = this.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
        if (fieldInfo == null || (fieldInfo.FieldType != typeof(SomeClass)) throw ArgumentException(nameof(suffix));
        SomeClass obj = fieldInfo.GetValue(this) as SomeClass;
        obj.CommonMethod();
    }
}

. , , . , , . , , , :

class Example
{
    Dictionary<string, SomeClass> _objects = new Dictionary<string, SomeClass>();

    public SomeClass()
    {
        _objects["A"] = new SomeClass();
        _objects["B"] = new SomeClass();
    }

    void CallObjectMethod(string key)
    {
        _objects[key].CommonMethod();
    }
}
+2

<string, Obj>, :

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

, , , Obj ObjFromDictionary...

...

+6

Source: https://habr.com/ru/post/1683506/


All Articles