如何使用反射获取对象的属性?

编程入门 行业动态 更新时间:2024-10-25 06:33:00
本文介绍了如何使用反射获取对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道我可以做到这一点

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

更多推荐

如何使用反射获取对象的属性?

本文发布于:2023-11-12 11:44:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   反射   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!