您如何使用反射获取类及其基类(在层次结构中)的所有属性?(C#) [英] How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)

查看:11
本文介绍了您如何使用反射获取类及其基类(在层次结构中)的所有属性?(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在拥有的是这样的:

So what I have right now is something like this:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public);

其中 obj 是某个对象.

问题是我想要的一些属性不在 obj.GetType() 中,它们在更进一步的基类之一中.如果我停止调试器并查看 obj,我必须挖掘一些基本"条目以查看我想要获得的属性.是否有一些绑定标志我可以设置让它返回那些或者我必须递归地挖掘 Type.BaseType 层次结构并对所有这些进行 GetProperties ?>

The problem is some of the properties I want aren't in obj.GetType() they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the Type.BaseType hierarchy and do GetProperties on all of them?

推荐答案

使用这个:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

当然正确的答案是 .GetProperties() 不带参数等价于 GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static ).BindingFlags.FlattenHierarchy 在这里没有任何作用.

Of course the correct answer is that of Jay. GetProperties() without parameters is equivalent to GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static ). The BindingFlags.FlattenHierarchy plays no role here.

这篇关于您如何使用反射获取类及其基类(在层次结构中)的所有属性?(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆