[英]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 dog = new Dog(); var children = dog.GetType().GetProperties(BindingFlags.Instance);
var children = dog.GetType().GetProperties(BindingFlags.Instance);
Why does the children array not contain the breed property?为什么 children 数组不包含品种属性?
By supplying only BindingFlags.Instance
, you can't get any properties at all, because you are not sending any access modifier predicate.通过仅提供
BindingFlags.Instance
,您根本无法获得任何属性,因为您没有发送任何访问修饰符谓词。
According to your needs, combine these flags with bitwise OR operator |
根据您的需要,将这些标志与按位 OR 运算符
|
结合使用
You can find the documentation here: https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8您可以在此处找到文档: 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:为了使其成为一个完整的答案,对仅包含
Breed
属性的数组的过滤由@const-phi 提供:
var result = children.Where(c => c.PropertyType.IsClass).ToArray(); // Const Phi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.