.NET Reflection and an array
I开发者_运维百科'm trying to get the value of a property that is a single dimensional array via reflection
I tried something like this: (try catches removed for clarity)
string[] fieldOrder;
PropertyInfo fieldOrderColumn;
fieldOrderColumn = targetType.GetProperty("OrderArray");
if (fieldOrderColumn == null)
throw new Exception(targetType.Name + " the OrderArray is null ");
fieldOrder = (string[])fieldOrderColumn.GetValue(targetType, null); //what should I use insted of this?
Clearly the last line is wrong, and is trying to get a non array object, I assumed a quick google and I'd be on my way, but I'm unable to find it. I don't know the lenght of the array at run time.
Any hints or links or help would be greatly appreciated.
You need to pass an instance of the type into GetValue
. If it is a static property, pass null
. Currently you are passing the type. I would expect to see (roughly):
Type targetType = obj.GetType();
...[snip]
fieldOrder = (string[])fieldOrderColumn.GetValue(obj, null);
Note that if you aren't sure of the type of array, you can just use Array
(instead of string[]
), or for single-dimension arrays IList
may be useful (and will handle arrays, lists etc):
IList list = (IList)fieldOrderColumn.GetValue(obj, null);
精彩评论