Il semble que vous ayez besoin d'une surcharge ToString
en Person
. En outre, ne pas exposer domaines publics comme ça. Utilisez 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 + "\"";
}
}
(modifier)
Voici votre demande (mais il nécessite des propriétés):
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();
}
}
Utilisation:
Console.WriteLine(ObjectPrettyPrint.ToString(new Person { FirstName, = "A", MI = "B", LastName = "C" }));
Nice @ bruno, mais toujours en attente d'autres entrées –
Voir la mise à jour de la réponse. –
yup, essayant maintenant ... –