dimanche 13 décembre 2015

c# access elements of list passed as object type (using reflection or any other method)

I want to access members of lists passed in as "object" (the function is handling other data types such as arrays as well). Unfortunately, while this works:

List<object> objectlist = new List<object> { "1", "2" };
object res = ((List<object>)((object)objectlist))[0];

this does not:

List<string> strlist = new List<string> { "1", "2" };
res = (string)((List<object>)((object)strlist))[0];

though it DOES work with arrays.

It does not appear to be possible to convert regular lists to List.

Is using reflection (but with GetMethods to avoid repeated string searches):

MethodInfo info = ((object)list).GetType().GetMethod("get_Item");
object s1 = (object)info.Invoke(((object)list), new object[] { 0 });

the only way to do this?

Dustin Soodak





Aucun commentaire:

Enregistrer un commentaire