-1

I have base class CommonClass - abstract parent. From it I have many derived classes, all have only new different members of same type ObjDescr. A shorten example

public class CommonClass
{
    // many common methods, handlers and properties
}

// many derived classes like this one
public class Orders : CommonClass
{
    public ObjDescr Date  { get; private set }
    public ObjDescr Place  { get; private set }
}

CommonClass service me well, but now i wanna to do an universal method, to which i can send any different derived child class. It will iterate some of the new derived members, knowing member names.

public SuperDuperUniversal( CommonClass UnknownDerived, string memb_name )
{
    // I do access to members now only WHEN i know the class
    Orders Order1 = (Orders)UnknownDerived;
    ObjDescr aPlace1 = Orders.Place;

    // I wanna to have access like
    ObjDescr aPlace2 = UnknownDerived.Get_ObjDescr_ByName(memb_name);
    string aPlaceName = aPlace2.Description;
}

I need to have access directly to member with name memb_name instance UnknownDerived.

Edit: I disagree that this question is duplicate with other. Solution is same, i agree. But question is different. I googled and search, before i ask it, and fail to find an answer. It will be handy, if someone else is looking to get class members of instance, from name, to find this answer.

TPAKTOPA
  • 2,462
  • 1
  • 19
  • 26
  • I tried to use GetMember, GetField, but they return member of type, not the member of **this** particular instance. – TPAKTOPA Feb 06 '15 at 09:38

1 Answers1

3

Using Reflection, you could get access to that property:

public void SuperDuperUniversal(CommonClass unknownDerived, string memb_name)
{
    var member = unknownDerived.GetType().GetProperty(memb_name).GetValue(unknownDerived, null) as ObjDescr;

    string desc = member.Description;
}
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • Seems **GetValue()**, where you can put the instance of derived object, is the method i missed to find in Reflection. I will try this, and Accept answer, if it works. – TPAKTOPA Feb 06 '15 at 09:44