开发者

How to get parent object from child object dynamically

Is it possible to get the parent object from a child object dynamically? Essentially, all I'm trying to accomplish is t开发者_如何转开发o dynamically retrieve the value of a property belonging to a child objects' parent. For example, something along the lines of the following:

public T GetParentProperty<T>(object oChildObject, string sPropertyName)
{
    ??? oOwner;
    PropertyInfo oOwnerInfo;
    T oPropertyValue;

    try
    {
        oPropertyValue = null;
        if (oChildObject != null)
        {
            oOwner = oChildObject.GetType().???;
            oOwnerInfo = oOwner.GetType().GetProperty(sPropertyName);
            if (oOwnerInfo != null)
                oPropertyValue = oOwnerInfo.GetValue(oOwner, null) as T;
        }
    }
    catch(Exception oEx)
    {
        Console.WriteLine(oEx);
    }

    return oPropertyValue;
}

Many thanks in advance!


Assuming you mean "Parent" as in the class that your child inherits from, you can use the BaseType property of the Type Class. If the BaseType property doesn't return exactly what you need, then you can look through the list of members at that link, and find the one that does. This is what you code example appears to be attempting.

Unfortunately, if you mean "Parent" as in the class that owns the reference to your child type, I don't think this can be done.

I'm wondering why you need this functionality though, as it is a strange need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜