I wrote a method that accepts a generic parameter and then it prints its properties. I use it to test my web service. It's working but I want to add some features that I don't know how to implement. I want to print values of lists, because now it just writes System.Collection.Generic.List1 which is expected.
Here is my code so far, this is working for basic types (int, double etc.):
static void printReturnedProperties<T>(T Object)
{
PropertyInfo[] propertyInfos = null;
propertyInfos = Object.GetType().GetProperties();
foreach (var item in propertyInfos)
Console.WriteLine(item.Name + ": " + item.GetValue(Object).ToString());
}
To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.
We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.
GetValue(Object) Returns the property value of a specified object.
Retrieving a custom attribute is a simple process. First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve.
You could do something like this:
static void printReturnedProperties(Object o)
{
PropertyInfo[] propertyInfos = null;
propertyInfos = o.GetType().GetProperties();
foreach (var item in propertyInfos)
{
var prop = item.GetValue(o);
if(prop == null)
{
Console.WriteLine(item.Name + ": NULL");
}
else
{
Console.WriteLine(item.Name + ": " + prop.ToString());
}
if (prop is IEnumerable)
{
foreach (var listitem in prop as IEnumerable)
{
Console.WriteLine("Item: " + listitem.ToString());
}
}
}
}
It will then enumerate through any IEnumerable and print out the individual values (I'm printing them one per line, but obviously, you can do different.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With