开发者

Is there a way to find the actual class a reflected field was defined in or find a common base class for child objects?

I have a field that is defined in a base class and when I use reflection on a child object, I want to retrieve the base class where the field is actually defined. Is there a way to d开发者_运维百科o this in C# .Net 4.0?

Alternatively, is there a way to dynamically find the common base class, given 2 different child classes?


The property FieldInfo.DeclaringType should point to the Type that actually defines the field.

This actually comes from MemberInfo so this will also work for properties, methods, etc..

For the second question. This is untested but should work:

public Type GetSharedBaseType(Type a, Type b)
{
    Type tempA = a;
    Type tempB = b;

    while (tempA != null)
    {
        while (tempB != null)
        {
            if (tempA == tempB)
                return tempA;

            tempB = tempB.BaseType;
        }

        tempA = tempA.BaseType;
        tempB = b;
    }

    return null;
}


To find which base class an object belongs to try this..

obj.GetType().DeclaringType;

To find out if two objects belongs to same base type you can do something like this.

//haven't compiled the code.. you can get the basic idea. Note that `System.Object` will always be the base class for every .Net Object
bool HaveSameBase(Object a, Object b)
{
    Type t = a.GetType();
    List<Type> aTypeList = new List<Type>();
    while(t.BaseType != System.Object)
        {
        aTypeList.Add(t.BaseType);
        t = t.BaseType;
        }

    Type s = b.GetType();
        while(s.BaseType != System.Object)
        {
        if(aTypeList.Any(item => item.Equals(s.BaseType)
             return true;
        s = s.BaseType;
        }

    return false;

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜