gpt4 book ai didi

c# - 通用对象调试器

转载 作者:太空狗 更新时间:2023-10-30 01:23:59 27 4
gpt4 key购买 nike

我正在尝试编写一个通用函数,我可以将对象传递给该函数,它将在 C# 中打印出所有属性和值。

我已经尝试了很多例子,比如 this , 还有一些像

    public void PrintProperties(object obj)
{
PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
if (obj == null) return;
string indentString = new string(' ', indent);
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(obj, null);
if (property.PropertyType.Assembly == objType.Assembly)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}

    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
Console.WriteLine("{0}={1}", name, value);
}

但是我想要在我的调试/日志文件中的一些对象包含字符串 [] 属性。所有这些示例都将这些输出为

System.String[]

如果我有一个像这样的对象

class Thing
{
public string Name { get; set; }

public int Number { get; set; }

public string[] Names { get; set; }
}

我希望在日志中看到像下面这样设置的任何值

Name: Test
Number: 3
Names[0]: Fred
Names[1]: John
Names[2]: Jimmy

感谢您的帮助 =]

这是我最终使用的类(class)

class Descriptor
{
public void PrintProperties(object obj)
{
PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
if (obj == null) return;
string indentString = new string(' ', indent);
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(obj, null);

if (propValue.GetType().IsArray)
{
object[] arrary = (object[]) propValue;
foreach (string value in arrary)
{
if (property.PropertyType.Assembly == objType.Assembly)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(value, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, value);
}
}
continue;
}

if (property.PropertyType.Assembly == objType.Assembly)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}

}

现在我将在这个类中使用 Log4Net,现在在我的整个 mvc3 站点中,我可以调用它并提供和发布 ViewModels 以在打开时进行全面调试

最佳答案

如果您不介意使用 Windows 窗体,有一个名为 PropertyGrid 的控件基本上可以满足您的需求:http://msdn.microsoft.com/en-us/library/system.windows.forms.propertygrid(v=vs.90).aspx

现在,对于您的具体问题,问题是您没有查看数组内部。您应该做的是查看每个属性的类型。如果是数组类型,则需要将值转换为 object[] 数组,然后遍历每个元素,而不是简单地打印值的 ToString() 输出.您还需要创建一个递归算法来查看每个属性并将其视为具有要迭代的属性的对象。如果您需要这方面的帮助,请告诉我。

关于c# - 通用对象调试器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10629072/

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