Thursday, July 14, 2011

mittels Reflection Name / Value Properties eines bel. Objektes zurückgeben

private Dictionary GetPropNameAndValuesAsDict(object o)
{
Dictionary d = new Dictionary();
foreach (PropertyInfo pi in o.GetType().GetProperties())
{
string s = "";
try
{
object oVal = pi.GetValue(o, null);
if (null != oVal) s = oVal.ToString();
}

catch (Exception ex)
{
s = ex.Message;
}
d.Add(pi.Name, s);
}
return d;
}

Umwandeln des obigen Dictonaries d in Stringliste:
List sl = (from de in d select de.Key + " = "+de.Value).ToList();

bzw. als Stringlist
private List GetPropNameAndValues(object o)
{
List sl = new List();
foreach (PropertyInfo pi in o.GetType().GetProperties())
{
string s = pi.Name;
try
{
object oVal = pi.GetValue(o, null);
if (null != oVal) s += "=" + oVal.ToString();
}

catch (Exception ex)
{
s += ":" + ex.Message;
}
sl.Add(s);
}
return sl;
}

No comments: