看來你需要ToString
超載Person
。此外,不要公開公衆這樣的字段。使用properties。
public class Person
{
public string FirstName { get; set; }
public string MI { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return "FirstName=\"" + FirstName + "\" p.MI=\"" + MI + "\" p.LastName=\"" + LastName + "\"";
}
}
(編輯)
這是你的請求(但它需要的屬性):
public static class ObjectPrettyPrint
{
public static string ToString(object obj)
{
Type type = obj.GetType();
PropertyInfo[] props = type.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var prop in props)
{
sb.Append(prop.Name);
sb.Append("=\"");
sb.Append(prop.GetValue(obj, null));
sb.Append("\" ");
}
return sb.ToString();
}
}
用法:
Console.WriteLine(ObjectPrettyPrint.ToString(new Person { FirstName, = "A", MI = "B", LastName = "C" }));
不錯@bruno,但仍在等待更多輸入 – 2009-08-07 09:25:03
查看最新的答案。 – 2009-08-07 09:47:25
y,現在正在嘗試... – 2009-08-07 09:58:12