T
trevorelbourne
Hi,
I am having trouble accessing the elements of an array using
reflection. This is the code I am having trouble with:
FieldInfo[] Fields = Obj.GetType().GetFields();
foreach (FieldInfo fi in Fields)
{
Object Temp = fi.GetValue(Obj);
if (Temp.GetType().IsArray)
{
// This is an array type.
MethodInfo GetLength =
Temp.GetType().GetMethod("GetLength");
Params = new Object[1];
int Length = (int)GetLength.Invoke(Temp, Params);
Object[] a = (Object[])Temp;
for (i = 0; i < Length; i++)
{
// Process array elements
}
}
}
I get a runtime error when executing the line:
Object[] a = (Object[])Temp;
The error message is:
InvalidCastException was not handled.
Specified cast is not valid.
Any ideas on what the problem is?
In the above case, it turns out the actual array is of type "Int32[]",
so if I modify the above line to become:
Int32[] a = (Int32[])Temp;
It works fine.
Any help greatfully received. Thanks.
Trevor.
I am having trouble accessing the elements of an array using
reflection. This is the code I am having trouble with:
FieldInfo[] Fields = Obj.GetType().GetFields();
foreach (FieldInfo fi in Fields)
{
Object Temp = fi.GetValue(Obj);
if (Temp.GetType().IsArray)
{
// This is an array type.
MethodInfo GetLength =
Temp.GetType().GetMethod("GetLength");
Params = new Object[1];
int Length = (int)GetLength.Invoke(Temp, Params);
Object[] a = (Object[])Temp;
for (i = 0; i < Length; i++)
{
// Process array elements
}
}
}
I get a runtime error when executing the line:
Object[] a = (Object[])Temp;
The error message is:
InvalidCastException was not handled.
Specified cast is not valid.
Any ideas on what the problem is?
In the above case, it turns out the actual array is of type "Int32[]",
so if I modify the above line to become:
Int32[] a = (Int32[])Temp;
It works fine.
Any help greatfully received. Thanks.
Trevor.