C#反射方法GetProperties(BindingFlags.Instance)不返回子类对象

时间:2020-03-24 17:17:49

标签: c# reflection

我试图在省略基本类型的同时检索对象的子类。

   public class Dog
    {
    public int Id {get;set;}
    public int Name {get;set;}
    public Breed Breed {get;set;}
    }

var dog = new Dog(); var children = dog.GetType()。GetProperties(BindingFlags.Instance);

为什么子数组不包含品种属性?

1 个答案:

答案 0 :(得分:2)

仅提供BindingFlags.Instance,就根本无法获得任何属性,因为您没有发送任何访问修饰符谓词。

根据您的需要,将这些标志与按位或运算符|

组合

您可以在此处找到文档:https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8

var children = dog.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

编辑:

不幸的是,枚举没有用于根据属性的值类型过滤属性的任何值。为了得到一个完整的答案,对仅包含Breed属性的数组的过滤由@ const-phi贡献:

var result = children.Where(c => c.PropertyType.IsClass).ToArray(); // Const Phi