2015-10-28 65 views
5

Desidero separare le variabili IEnumerable in base al loro tipo. Il mio codice è simile a questo:come ottenere solo il tipo di Enumerable?

if (type is IEnumerable) 
{ 
    var listGenericType = type.GetType().GetGenericTypeDefinition().Name; 
    listGenericType = listGenericType.Substring(0, listGenericType.IndexOf('`')); 
    if (listGenericType == "List") { 
     //do something 
    } 

    else if (listGenericType == "HashSet") { 
     //do something 
    } 
} 

Quando uso type.GetType().GetGenericTypeDefinition().Name, il listGenericType è come List`1 o HashSet`1 ma lo voglio come List o HashSet. Quindi, ho usato Substring per gestire questo problema!

È comunque possibile gestire questo problema senza postProcessing string tipo? Intendo qualcosa come sotto il codice:

if (type is IEnumerable) 
{ 
    var listGenericType = type.GetType().GetGenericTypeDefinitionWithoutAnyNeedForPostProcessing(); 
    if (listGenericType == "List") { 
     //do something 
    } 

    else if (listGenericType == "HashSet") { 
     //do something 
    } 
} 
+1

https://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx –

risposta

5

Non è necessario confrontarlo con una stringa. Dal momento che i rendimenti GetGenericTypeDefinition() un tipo, tutto quello che dovete fare è confrontare contro un tipo utilizzando l'operatore typeof, come ad esempio:

if (type is IEnumerable) 
{ 
    var listGenericType = type.GetType().GetGenericTypeDefinition(); 

    if (listGenericType == typeof(List<>)) { 
     //do something 
    } 
    else if (listGenericType == typeof(HashShet<>)) { 
     //do something 
    } 
} 

Come @nopeflow gentilmente segnalato di seguito, se il tipo, se non un tipo generico quindi GetGenericTypeDefinition() genererà un InvalidOperationException. Assicurati di avere un account per quello.

+3

E 'adirato per citare che un certo tipo può implementare 'IEnumerable' ma quel tipo non è una generica. (Il tipo può implementare 'IEnumerable' ma non' IEnumerable '.... Quindi,' GetGenericTypeDefinition' genererà 'InvalidOperationException'.) – pwas

+0

Grazie, ho modificato la mia risposta – kskyriacou

0

Supponendo che stiate cercando solo tipi generici, credo che questo potrebbe aiutarvi.

  List<int> someObject = new List<int>(); 
      Type currentType = someObject.GetType(); 

      if (currentType.IsGenericType) 
      { 
       if (currentType.GetGenericTypeDefinition() == typeof(List<>)) 
       { 
        // Do something 
       } 
       else if (currentType.GetGenericTypeDefinition() == typeof(HashSet<>)) 
       { 
        // Do something else 
       } 
      } 
Problemi correlati