samedi 12 octobre 2019

How to tell if IEnumerable object is array or List at runtime?

I take all fields of an object and check for each field if it implements IEnumerable. If so, I have to distinguish between Array, List and any other IEnumerable because I have to get their element type and unfortunately there are different implementations for each.

else if (typeOfField.GetInterface(nameof(IEnumerable)) != null)
                {
                    object returnedEnum;

                    if (fi.GetValue(original) is Array)     //this is the problematic line
                    {
                        returnedEnum = typeof(Duplicator)
                        .GetMethod("Get_Copy_ofIEnumerable")
                        .MakeGenericMethod(fi.GetValue(original).GetType().GetElementType())
                        .Invoke(null, new object[] { fi.GetValue(original) });
                    }
                    else
                    {
                        returnedEnum = typeof(Duplicator)
                        .GetMethod("Get_Copy_ofIEnumerable")
                        .MakeGenericMethod(fi.GetValue(original).GetType().GetGenericArguments()[0])
                        .Invoke(null, new object[] { fi.GetValue(original) });
                    }

                    fi.SetValue(copy, returnedEnum);
                }

As you can see, Array needs GetElementType while List needs GetGenericArguments.

So far I have tried putting int[], double[] and List<T> fields into the test and all three go to else block which results in error for arrays.





Aucun commentaire:

Enregistrer un commentaire