Feedback

C# - Inspect an object by reflection

Veröffentlicht von am 11/20/2015
(0 Bewertungen)
The method Inspect returns all properties and their values as a string (purpose: debugging or logging).

Example:
Console.WriteLine(
Inspect(new { Lastname = "Peters", Firstname = "Bob" }));
Console.WriteLine(
Inspect(new DateTime(2015, 11, 20)));
public static string Inspect(object o)
{
    var result = "";
    var t = o.GetType();
    var infos = t.GetProperties();

    foreach (PropertyInfo info in infos)
    {
        if (info.CanRead)
        {
            var value = info.GetValue(o);
            result += info.Name + " = " + (value == null ? "null" : value.ToString()) + " | ";
        }
    }
    return result;
}
Abgelegt unter Reflection, Debugging, Logging.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!