dimanche 28 juin 2015

C# Set array memberInfo without generic cast

if(fieldInfo.FieldType.IsArray)
{
    Type elementType = fieldInfo.FieldType.GetElementType();
    obj[] objs = MyCustomConverter.Convert(elementType, IEnumerable<string> input);
    field.SetValue(target,objs);
}

The SetValue step will throw an exception because the value(objs) to be set does not match the specific type. But the hardest part is that I don't know what type the array exactly is. All I have is non-generic. So I cannot call something like Cast<T> (I don't have that generic T but I have typeof(T)). And Array.ConvertAll(objs,obj=> Convert.ChangeType(obj, elementType)) makes no sense since it still returns object[] and my custom converter has already converted the input elements to the right element type!! It's just that the array itself is wrapped. Is there a way to do such hack as object array = SomeFunc(Type arrayType, object[] elements); ?

What should I do to set the array field successfully? (I hope I made myself clear :P)





Aucun commentaire:

Enregistrer un commentaire