G
Guest
I'm trying to write a utility that will use Reflection to examine any data
model I pass it and correctly map out this model into a tree structure. When
I say "any" [data model], in fact there will only be 3 types of items in the
very hierarchical data model:
- Classes (and nested classes)
- Collections
- Properties
I've successfully written the Reflection code to handle any combination of
classes and properties but I'm confused about what to do when I encounter a
collection. Here's some starting code I've written:
-----------------------------------------------------------------------------
Type modelType = model.GetType();
FieldInfo[] fields = modelType.GetFields();
for(int i = 0; i < fields.Length; i++)
{
Type fieldType = fields.FieldType;
object obj = fields.GetValue(model);
}
-----------------------------------------------------------------------------
Remember that I don't know ahead of time what types of collections I'll be
encountering. So though the 'fieldType' variable seems to correctly identify
the type of the collection, I can't figure out how to cast 'obj' to its true
type ... and then from there I could examine the elements that populate the
collection.
So I'm wondering two things:
1. Is what I'm asking to do possible?
2. Am I close or barking up the wrong tree?
model I pass it and correctly map out this model into a tree structure. When
I say "any" [data model], in fact there will only be 3 types of items in the
very hierarchical data model:
- Classes (and nested classes)
- Collections
- Properties
I've successfully written the Reflection code to handle any combination of
classes and properties but I'm confused about what to do when I encounter a
collection. Here's some starting code I've written:
-----------------------------------------------------------------------------
Type modelType = model.GetType();
FieldInfo[] fields = modelType.GetFields();
for(int i = 0; i < fields.Length; i++)
{
Type fieldType = fields.FieldType;
object obj = fields.GetValue(model);
}
-----------------------------------------------------------------------------
Remember that I don't know ahead of time what types of collections I'll be
encountering. So though the 'fieldType' variable seems to correctly identify
the type of the collection, I can't figure out how to cast 'obj' to its true
type ... and then from there I could examine the elements that populate the
collection.
So I'm wondering two things:
1. Is what I'm asking to do possible?
2. Am I close or barking up the wrong tree?