I am trying to use reflection to output the fields (names and values) of an
arbitrary object -- an object dump to a TreeView.
It works pretty well, but I am having trouble with generic lists, like
List<char>.
What I have working is :
Type type = newObj.GetType(); //newObj is what I'm trying to dump
fieldInfo = new List<ObjFields>(200); //text representation of
the fields
//code to get info of a generic list:
if (type.Namespace == "System.Collections.Generic")
{
FieldInfo items =
type.GetField("_items",
BindingFlags.Instance |
BindingFlags.NonPublic );
if (items != null)
{
System.Array array =
items.GetValue(newObj) as System.Array;
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
//get the value and name
fieldInfo.Add(new ObjFields(
array.GetValue(i), //field value
"[" + i.ToString() + "]")); //field "name"
}
return;
}
}
which works fine. However, I am getting the collection by keying on
the name "_items" (in Type.GetField), which is dangerous since MS might
change the internals of the generic list.
What I'd like to do is cast the generic list to something like an
Object[], or System.Array, or convert it to such, without compiling in the
types of the members of the generic list.
I.E. how can I go from a List<to an Object[]/Array without knowing the
types of the elements of the generic list?
Clearly,
Array newArray = newObj as System.Array; //where
newObj is of type List<?>
does not work, but that's the effect I am after.
--
Fred Mellender, Rochester, NY