I’m trying to make a model reflection tool. I have come a long way so far but now i’m stuck.
I have this
public static void RenderModelList(List<T> modelList)
{
foreach (T model in modelList)
{
PropertyInfo[] properties = model.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(model, null);
//Check if the property is a collection and do recursion
if (propValue != null)
{
if (isCollection(propValue))
{
//This only works for Lists of the same <T>
List<T> li = Convert.ChangeType(propValue, propValue.GetType()) as List<T>;
if (li != null)
{
if (li.Count > 0)
{
RenderModelList(li, loop);
}
}
else
{
//Its another type what to do?
// Create a List<> of unknown type??
}
}
}
}
}
}
My problem is that if I pass this method a List<Persons> and the Person has a property which is a List<Cars> – I can’t use Convert.ChangeType – because this is not the T.
So how do I loop thrugh a “List” and get access to the properties of this object ?
It seems to me that your method can be a lot more loosely typed:
Then you just need to cast to
IEnumerable, not a specific sequence or list type.