1
class A
{
    public string proprt1 { get; set; }
    public string proprt2 { get; set; }

    public A(string p1,string p2)
    {
        proprt1 = p1;
        proprt2 = p2;
    }
}

class B : A
{
    public B(string p1,string p2):base(p1,p2)
    {
    }
}

class Q
{
    public B b = new B("a","b");
}

I want to know if the member of class Q (ie., Class B) is compatible with Class A by Reflection

private void someMethod()
{
    Q q = new Q();
    Type type = q.GetType();

    foreach (FieldInfo t in type.GetFields())
    {
        //I am stuck here
        //if (t.GetType() is A)
        //{}
    }
}

and then I want to iterate through the inherited properties of B..

How do I do this? I am new to reflection...

techBeginner
  • 3,792
  • 11
  • 43
  • 59
  • 4
    Take a look at http://stackoverflow.com/questions/8699053/how-to-check-if-a-class-inherits-another-class-without-instantiating-it for how you can check if a class can be cast to another type. – PhonicUK Aug 09 '12 at 10:39
  • @PhonicUK the reference you gave, uses two known types to check, but in my case the derived class type is unknown and I am trying to find it by reflection.. – techBeginner Aug 09 '12 at 11:24

1 Answers1

1

This works in my test app.

static void Main(string[] args) {
    Q q = new Q();
    Type type = q.GetType();

    Type aType = typeof(A);

    foreach (var fi in type.GetFields()) {
        object fieldValue = fi.GetValue(q);
        var fieldType = fi.FieldType;
        while (fieldType != aType && fieldType != null) {
            fieldType = fieldType.BaseType;
        }
        if (fieldType == aType) {
            foreach (var pi in fieldType.GetProperties()) {
                Console.WriteLine("Property {0} = {1}", pi.Name, pi.GetValue(fieldValue, null));
            }
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}
Maarten
  • 22,527
  • 3
  • 47
  • 68