Ho un metodo di estensione per convertire una lista generica in stringa.Come rilevare se un oggetto è di tipo generico Elenco e trasmettere al tipo richiesto?
public static string ConvertToString<T>(this IList<T> list)
{
StringBuilder sb = new StringBuilder();
foreach (T item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
Ho un oggetto che è di tipo oggetto che contiene una lista; l'elenco potrebbe essere List<string>
, List<int>
, List<ComplexType>
qualsiasi tipo di elenco.
Esiste un modo per rilevare che questo oggetto è un elenco generico e quindi inoltrato a quel tipo di elenco generico specifico per chiamare il metodo ConvertToString
?
//ignore whats happening here
//just need to know its an object which is actually a list
object o = new List<int>() { 1, 2, 3, 4, 5 };
if (o is of type list)
{
string value = (cast o to generic type).ConvertToString();
}
un elenco non è un array; anche questo non aiuta l'OP a trovare il 'T' o ad invocare il metodo –