jeudi 21 janvier 2016

convert dynamically object to an array of dynamic type in c#

I have 2 types :

    public class Type1
    {
        public string Name { get; set; }
    }

    public class Type2
    {
        public string Name { get; set; }
    }

I have a list of elements (each element is an object type). Some elements could be an array. (an array could be a type1[] or a type2[])

My goal is to :
1-iterate on my list of elements
2-determine which are type1[]array pr type2[] array
3-get the Name value property for element of those previous array

This is what I have done :

    foreach (var Myobject in MyList)
    {
        if (myObject.GetType().IsArray)
        {
            var elementType = myObject.GetType().GetElementType()// should me return the element type, ie Type1 or Type2

            //This is where I am stuck, I know that my object is an array but I cannot cast if in type1[] or type2[] array by using elementType
            //The following is not working
            elementType[] myArrat = (elementType[])myObject;

            // And I don't want to hardwrite each case for each possible type like this :
            Type1[] myArrat = (Type1[])myObject;
            Type2[] myArrat = (Type2[])myObject;
            // I want to use the elementType that I got previously

        }
    }

Thanks in advance for your help.





Aucun commentaire:

Enregistrer un commentaire