gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:14:59 24 4
gpt4 key购买 nike

我需要创建一个函数来获取对象(包括子对象)的所有属性,这是为了我的错误记录功能。现在我的代码总是返回 0 个属性。请让我知道我做错了什么,谢谢!

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;
}

这是对象的样子: alt text alt text

最佳答案

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

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 .

关于c# - 反射类获取任何对象的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com