V
Velislav
Hi, I've got the following piece of code:
string GetPropertyValue(object jobCard, string propertyName,
int index)
{
PropertyInfo property =
jobCard.GetType().GetProperty(propertyName);
if (property.PropertyType.IsArray)
{
object[] propertyValue =
(object[])property.GetValue(jobCard, null);
return propertyValue[index].ToString();
}
else
{
return property.GetValue(jobCard, null).ToString();
}
}
all it does is take an object (jobCard), and returns a string
representation of the given property (propertyName). If that property
is an array, it returns the value of the array item at the specified
index (index).
the jobCard parameter is a reference to an object of class JobCard
which looks something like this:
public class JobCard
{
...
int[] specification;
RawMaterial[] rawMaterials;
...
int[] Specification { get { return specification; } set
{ specification = value; } }
RawMaterial[] RawMaterials { get { return rawMaterials; } set
{ rawMaterials = value; } }
...
}
the following happens when i invoke my method:
GetPropertyValue(jobCard, "RawMaterials", 1); // Works 100%
GetPropertyValue(jobCard, "Specification", 1); //Error: Unable to cast
object of type 'System.Int32[]' to type 'System.Object[]'.
Note: Both the RawMaterial[] and int[] arrays contain an element with
index 1.
obviously the error is thrown when i cast the result of
PropertyInfo.GetValue()... but I see no reason why I shouldn't be able
to cast int[] to object[]
Any ideas?
Thanks
string GetPropertyValue(object jobCard, string propertyName,
int index)
{
PropertyInfo property =
jobCard.GetType().GetProperty(propertyName);
if (property.PropertyType.IsArray)
{
object[] propertyValue =
(object[])property.GetValue(jobCard, null);
return propertyValue[index].ToString();
}
else
{
return property.GetValue(jobCard, null).ToString();
}
}
all it does is take an object (jobCard), and returns a string
representation of the given property (propertyName). If that property
is an array, it returns the value of the array item at the specified
index (index).
the jobCard parameter is a reference to an object of class JobCard
which looks something like this:
public class JobCard
{
...
int[] specification;
RawMaterial[] rawMaterials;
...
int[] Specification { get { return specification; } set
{ specification = value; } }
RawMaterial[] RawMaterials { get { return rawMaterials; } set
{ rawMaterials = value; } }
...
}
the following happens when i invoke my method:
GetPropertyValue(jobCard, "RawMaterials", 1); // Works 100%
GetPropertyValue(jobCard, "Specification", 1); //Error: Unable to cast
object of type 'System.Int32[]' to type 'System.Object[]'.
Note: Both the RawMaterial[] and int[] arrays contain an element with
index 1.
obviously the error is thrown when i cast the result of
PropertyInfo.GetValue()... but I see no reason why I shouldn't be able
to cast int[] to object[]
Any ideas?
Thanks