如何使用输出窗口写入对象的所有成员?Trace.WriteLine 使用方法 ToString 并且不输出所有成员。是否有 API 可以在不编写自己的代码的情况下做到这一点?
问问题
1376 次
3 回答
4
你可以这样做:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var m = new MyClass { AString = "somestring", AnInt = 60 };
Console.WriteLine(GetObjectInfo(m));
Console.ReadLine();
}
private static string GetObjectInfo(object o)
{
var result = new StringBuilder();
var t = o.GetType();
result.AppendFormat("Type: {0}\n", t.Name);
t.GetProperties().ToList().ForEach(pi => result.AppendFormat("{0} = {1}\n", pi.Name, pi.GetValue(o, null).ToString()));
return result.ToString();
}
}
public class MyClass
{
public string AString { get; set; }
public int AnInt { get; set; }
}
}
于 2009-12-04T10:44:09.787 回答
2
它可能通过反射遍历成员。
于 2009-12-04T09:36:57.390 回答
0
特定对象上的 ToString() 方法被调用,如果该方法已被覆盖以显示所有成员,那么很好。然而,并非所有对象都实现了它们的 ToString() 方法,在这种情况下,该方法返回对象类型信息。
与其调用 ToString() ,不如编写一个自定义函数,该函数使用反射来枚举对象成员,然后输出。
编辑:这个函数将返回给定对象的属性,添加方法,事件你需要的一切。(它在 VB 中,在这台工作 PC 上没有 C#)
Function ListMembers(ByVal target As Object) As String
Dim targetType As Type = target.GetType
Dim props() As Reflection.PropertyInfo = targetType.GetProperties
Dim sb As New System.Text.StringBuilder
For Each prop As Reflection.PropertyInfo In props
sb.AppendLine(String.Format("{0} is a {1}", prop.Name, prop.PropertyType.FullName))
Next
Return sb.ToString
End Function
于 2009-12-04T09:37:50.070 回答