4

I found something similar on another question but i couldnt solve my problem as i'm still quite new in c#.

i have

System.Type type; // for example int[]
System.Type elementType = type.GetElementType(); //for example int

and a List that i need to cast to int[]

object valueObj; //is my List<object> i want to cast to int[]

I'm trying the following:

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 });

in the last line i get this runtime exception

InvalidCastException: Cannot cast from source type to destination type. System.Linq.Enumerable+c__Iterator01[System.Int32].MoveNext () System.Collections.Generic.List1[System.Int32].AddEnumerable (IEnumerable`1 enumerable)

as a last thing i need to assign the casteObject to a privateField using

field.SetValue(this, castedObject);

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.

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

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

i will double check and get with more info


the problem is that when press enter or space it is taking that also as input

 #include <iostream>
 include <string>
 using namespace std;
   main()
 {

string a[10];
int i;
 int N;
 cin >> N >> std::ws;
for (i=0; i<N; i++)
{

getline(cin,a[i]);

}
 return 0;
}
4

2 に答える 2

1

うーん、ソースがList<object>あり、その長さを取得できます。

タイプと長さでArray.CreateInstanceを呼び出すことができます。あとは、項目を 1 つずつ移動するだけです。

なぜこれに linq を使用するのですか?

于 2013-06-14T17:43:47.667 に答える