【问题标题】:check if the type is compatible with parent and then iterate through its properties by reflection检查类型是否与父类型兼容,然后通过反射遍历其属性
【发布时间】:2012-08-06 13:37:16
【问题描述】:
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");
}

我想知道 Q 类的成员(即 B 类)是否通过反射与 A 类兼容

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)
        //{}
    }
}

然后我想遍历 B.. 的继承属性。

我该怎么做?我是反思的新手...

【问题讨论】:

  • 查看stackoverflow.com/questions/8699053/…,了解如何检查一个类是否可以转换为另一种类型。
  • @PhonicUK 您提供的参考,使用两种已知类型来检查,但在我的情况下,派生类类型是未知的,我试图通过反射找到它..

标签: c# inheritance reflection


【解决方案1】:

这适用于我的测试应用程序。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多