Struggling with the following problem. I have an attribute that defines the name of the key in the database table. Using reflection, I initialize the value of a property or a field with that attribute. Everything is great until I define my property as an array:
[ConfigurationKey("TestArray")]
public int[] Array { get; set; }
Assuming that values stored in the table are comma-delimited strings, I am using the following to create an array:
return valueString.Split(',').Select(s => Convert.ChangeType(s, memberType.GetElementType())).ToArray();
This does create an array of elements but only array of Objects. As a result when I use FieldInfo or PropertyInfo to set a value, it throws with the exception “Cannot assign Object[] to Int32[]“.
Any ideas?
Well given that
Convert.ChangeTypeis declared to returnObject, I don’t think this is particularly surprising.ToArray()will create an array with the same element type as the input sequence, andSelectis going to return anIEnumerable<object>in this case.One option is to call
Cast(and thenToArray) using reflection. To be honest, it’s probably going to be easiest to put everything into a single generic method, and call that by reflection:Then you’d need: