Note that there are some explanatory texts on larger screens.

plurals
  1. POCast List<object> to unknown T[] using reflection
    primarykey
    data
    text
    <p>I found something similar on another question but i couldnt solve my problem as i'm still quite new in c#.</p> <p>i have</p> <pre><code>System.Type type; // for example int[] System.Type elementType = type.GetElementType(); //for example int </code></pre> <p>and a List that i need to cast to int[]</p> <pre><code>object valueObj; //is my List&lt;object&gt; i want to cast to int[] </code></pre> <p>I'm trying the following:</p> <pre><code>MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast") .MakeGenericMethod( new System.Type[]{ elementType } ); MethodInfo toArrayMethod = typeof(Enumerable).GetMethod("ToArray") .MakeGenericMethod( new System.Type[]{ elementType } ); var castedObjectEnum = castMethod.Invoke(null, new object[] { valueObj }); var castedObject = toArrayMethod.Invoke(null, new object[] { castedObjectEnum }); </code></pre> <p>in the last line i get this runtime exception</p> <p>InvalidCastException: Cannot cast from source type to destination type. System.Linq.Enumerable+c__Iterator0<code>1[System.Int32].MoveNext () System.Collections.Generic.List</code>1[System.Int32].AddEnumerable (IEnumerable`1 enumerable)</p> <p>as a last thing i need to assign the casteObject to a privateField using</p> <pre><code>field.SetValue(this, castedObject); </code></pre> <p>Edit: I will try and get more info on that but to better explain what i'm trying to do i will explain the use case.</p> <p>i serialize to disk in json some class fields, and then when i deserialize i get back a List where i serialize a base array of int/bools/string</p> <p>I'm doing the serialization and deserialization by marking fields with a custom attribute, and i want to be able to serialize both Array and Lists of any basic type</p> <p>i will double check and get with more info</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload