反射类获取任何对象的所有属性

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

我需要作出规定得到一个对象(包括儿童对象)的所有properies函数这是我的错误日志记录功能。 现在我的代码总是返回0的属性。 请让我知道我做错了什么,谢谢!

I need to make a function that get all the properies of an object (including an children objects) This is for my error logging feature. Right now my code always returns 0 properties. Please let me know what I'm doing wrong, thanks!

public static string GetAllProperiesOfObject(object thisObject) { string result = string.Empty; try { // get all public static properties of MyClass type PropertyInfo[] propertyInfos; propertyInfos = thisObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);//By default, it will return only public properties. // sort properties by name Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name)); // write property names StringBuilder sb = new StringBuilder(); sb.Append("<hr />"); foreach (PropertyInfo propertyInfo in propertyInfos) { sb.AppendFormat("Name: {0} | Value: {1} <br>", propertyInfo.Name, "Get Value"); } sb.Append("<hr />"); result = sb.ToString(); } catch (Exception exception) { // to do log it } return result; }

这里的对象是什么样子:

here's what the object looks like:

推荐答案

如果你想要的所有属性,请尝试:

If you want all of the properties, try:

propertyInfos = thisObject.GetType().GetProperties( BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public | BindingFlags.Static | BindingFlags.Instance // Get instance + static | BindingFlags.FlattenHierarchy); // Search up the hierarchy

有关详细信息,请参阅BindingFlags 。

For details, see BindingFlags.

更多推荐

反射类获取任何对象的所有属性

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

发布评论

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

>www.elefans.com

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