.net 在类实例中深度查找属性类型

.net 在类实例中深度查找属性类型,.net,reflection,system.reflection,.net,Reflection,System.reflection,我有一个方法可以解析xml并从该xml创建指定类型的对象。 这都是使用泛型来完成的,以便对所有类型都有一个通用的方法 我的问题是,我希望使用属性的类型名(而不是名称)在各种类中搜索属性。 假设属性有一个类型“type1”,那么下面声明了一些类定义: class foo1 { type1 prop1{get;set;} } class foo2 { foo1 prop2{get;set;} } class foo3:foo2 { type2 prop3{get;set;} } 对

我有一个方法可以解析xml并从该xml创建指定类型的对象。 这都是使用泛型来完成的,以便对所有类型都有一个通用的方法

我的问题是,我希望使用属性的类型名(而不是名称)在各种类中搜索属性。 假设属性有一个类型“type1”,那么下面声明了一些类定义:

class foo1
{
  type1 prop1{get;set;}
}

class foo2
{
  foo1 prop2{get;set;}
}

class foo3:foo2
{
  type2 prop3{get;set;}
}
对于上述所有声明的类,如果我创建对象,那么我希望访问上述类的每个实例的
type1
类型属性,即我应该能够从
foo1
foo2
foo3
类的对象中获取声明为
type1
的属性值。我真的需要一种通用的方法来实现这一点,因为类可能会增加。

这里有一种方法几乎可以实现这一点。缺少的是,使用反射,BindingFlags.FlatterHierarchy不会返回父类的私有方法。将这些类型标记为受保护或公共将解决此问题。(您还可以手动遍历基类以读取私有成员。)

如果要查找程序集中声明给定类型属性的所有类型,可以编写如下方法:

// using System.Reflection

public IEnumerable<Type> GetTypesWithPropertyOfType(Assembly a, Type t)
{
    BindingFlags propertyBindingFlags = BindingFlags.Public 
                                       | BindingFlags.NonPublic 
                                       | BindingFlags.Instance 
                                       | BindingFlags.FlattenHierarchy;

    // a property is kept if it is assignable from the type
    // parameter passed in            
    MemberFilter mf = (pi, crit)=>
          (pi as PropertyInfo)
          .PropertyType
          .IsAssignableFrom(t);

    // a class is kept if it contains at least one property that
    // passes the property filter.  All public and nonpublic properties of
    // the class, and public and protected properties of the base class,
    // are considered
    Func<Type, bool> ClassFilter = 
        c=>c.FindMembers(MemberTypes.Property, propertyBindingFlags, mf, null)
            .FirstOrDefault() != null;

    // return all classes in the assembly that match ClassFilter
    return
        a.GetTypes()
        .Where(c=>c.IsClass)
        .Where(ClassFilter);
}
这打印出了foo1。如果定义foo类的代码被修改为(a)使
foo1.prop1
公开或受保护,以及(b)使
foo2
foo1
继承,则上述代码打印:

foo1
foo2
foo3

正如预期的那样。

如何修改上述方法以获得类型为“type1”的属性值。?请让我知道。我的目的是获取任何类的实例的值。嘿,我得到了另一个解决方案(非反射方法),因为我认为投入精力太多了。但是谢谢你的帮助。
foo1
foo2
foo3