Я хочу написать метод, который преобразует коллекцию элементов универсального типа в удобочитаемую строку. Этот метод также должен работать с вложенными коллекциями. Я не нашел лучшего подхода, чем проверка того, являются ли элементы сами по себе коллекциями, и если да, то рекурсивный вызов метода для каждого элемента. Но я не понимаю, как привести элемент универсального типа к коллекции так, чтобы его принял компилятор.
Ниже я привожу код своего метода. Я отметил строчку, которая меня интересует, комментарием. В настоящее время, если тип элемента, например, int[], метод пытается привести элемент к IEnumerable — как я могу заставить метод вместо этого привести элемент типа int[] к IEnumerable?
public static string DeepTransform(IEnumerable input)
{
string output = "[";
foreach (T first_element in input) // foreach is purely for checking the first element: IEnumerable is not necessarily an indexed type.
{
if (first_element != null && first_element.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable)))
{
foreach (T element in input)
{
output = $"{output}{DeepTransform((IEnumerable)element)}, "; // There is mistake
}
}
/* In fact, the entire program is located in the if and else blocks: again, the first foreach is purely for checking the first element. */
else
{
foreach (T element in input)
{
output = $"{output}{element}, ";
}
}
return $"{output[0..(output.Length - 2)]}]";
}
return "Roses are red and violets are blue..."; // This will almost never be returned.
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... collection