techBeginner
techBeginner

Reputation: 3850

check if the type is compatible with parent and then iterate through its properties by reflection

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...

Upvotes: 1

Views: 149

Answers (1)

Maarten
Maarten

Reputation: 22945

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();
}

Upvotes: 1

Related Questions