fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5.  
  6. public class Test
  7. {
  8. public int[] intValues;
  9.  
  10. public static void Main()
  11. {
  12. string[] arrayData = { "20", "30", "40" };
  13. FieldInfo f = typeof(Test).GetField("intValues");
  14. Type t = f.FieldType.GetElementType();
  15. Test test = new Test();
  16. f.SetValue(test, GenericConvert.ChangeArrayType(arrayData, t));
  17.  
  18. Console.WriteLine("int values: {0}",
  19. string.Join(", ", test.intValues.Select(v => v.ToString()))
  20. );
  21. }
  22. }
  23.  
  24. public class GenericConvert
  25. {
  26. public static object ChangeArrayType<S>(IEnumerable<S> a, Type t)
  27. {
  28. MethodInfo methodDefinition = typeof(GenericConvert).GetMethod("ChangeArrayTypeGeneric");
  29. MethodInfo method = methodDefinition.MakeGenericMethod(t, typeof(S));
  30. return method.Invoke(null, new object[] { a });
  31. }
  32.  
  33. public static T[] ChangeArrayTypeGeneric<T, S>(IEnumerable<S> a)
  34. {
  35. return a.Select(x => (T) Convert.ChangeType(x, typeof(T))).ToArray();
  36. }
  37. }
Success #stdin #stdout 0.05s 24512KB
stdin
Standard input is empty
stdout
int values: 20, 30, 40