Hier is how to print the properties and fields of a certain object
public static string DisplayObjectInfo(Object o)
{
StringBuilder sb = new StringBuilder();
// Include the type of the object
System.Type type = o.GetType();
sb.Append("Type: " + type.Name);
// Include information for each Field
sb.Append("\r\n\r\nFields:");
System.Reflection.FieldInfo[] fi = type.GetFields();
if (fi.Length > 0)
{
foreach (FieldInfo f in fi)
{
sb.Append("\r\n " + f.ToString() + " = " + f.GetValue(o));
}
}
else
sb.Append("\r\n None");
// Include information for each Property
sb.Append("\r\n\r\nProperties:");
System.Reflection.PropertyInfo[] pi = type.GetProperties();
if (pi.Length > 0)
{
foreach (PropertyInfo p in pi)
{
sb.Append("\r\n " + p.ToString() + " = " +
p.GetValue(o, null));
}
}
else
sb.Append("\r\n None");
return sb.ToString();
}
1 comment:
Yup, reflection is one of the most powerfull sides of .NET.
One thing, I found in the example code - it is listing only public fields and properties.
If you want to list the methods as well, you can try using:
MethodInfo[] mi = type.GetMethods();
or, you could use
MemberInfo[] mmi = type.GetMembers();
which will return any public methods, fields or properties, including any public constructors.
I'll make a post soon, about System.Reflection and how to use it to create a plugin-extendable application.
Ya-Taaa!
Post a Comment