本文介绍了如何使用反射获取对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以做到这一点
I know I can do this
foreach (PropertyInfo property in myobject.GetType().GetProperties()) { if (property.DeclaringType.ToString() == myobject.GetType().ToString()) { // only have my object properties here // and not parent of my object properties } }但是我怎样才能只是获得 myobject 的属性而不是父对象的属性?即不必执行额外的 if 语句.
But how can I just get the properties of myobject and not those of the parent as well? ie not have to do that extra if statement.
编辑答案,(感谢@Greg Beech)这有效:-
edited for answer, (Thanks @Greg Beech) This worked:-
foreach (PropertyInfo property in myobject.GetType().GetProperties (BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)) { // only properties of my object not parent of myobject }我也找到了这个链接msdn.microsoft/en-us/library/4ek9c21e.aspx
推荐答案查看 BindingFlags.DeclaredOnly 并将其传递给 GetProperties(您可能希望将其合并至少使用 BindingFlags.Public 和 BindingFlags.Instance).
Check out BindingFlags.DeclaredOnly and pass that to GetProperties (you'll probably want to combine it with BindingFlags.Public and BindingFlags.Instance at least).
更多推荐
如何使用反射获取对象的属性?
发布评论