简体   繁体   中英

C# Reflection method GetProperties(BindingFlags.Instance) not returning child class objects

I am attempting to retrieve the child classes of an object while omitting primitive types.

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

Why does the children array not contain the breed property?

By supplying only BindingFlags.Instance , you can't get any properties at all, because you are not sending any access modifier predicate.

According to your needs, combine these flags with bitwise OR operator |

You can find the documentation here: https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8

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

EDIT:

Unfortunately, the enumeration does not have any value for filtering the properties according to their value types. To make this a complete answer, the filtering to an array containing only the Breed property is as contributed by @const-phi:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM