2012-11-02 11 views
5

Diciamo dichiaro quanto segueCome determinare se un oggetto implementa IDictionary o IList di qualsiasi tipo

Dictionary<string, string> strings = new Dictionary<string, string>(); 
List<string> moreStrings = new List<string>(); 

public void DoSomething(object item) 
{ 
    //here i need to know if item is IDictionary of any type or IList of any type. 
} 

Ho provato con:

item is IDictionary<object, object> 
item is IDictionary<dynamic, dynamic> 

item.GetType().IsAssignableFrom(typeof(IDictionary<object, object>)) 
item.GetType().IsAssignableFrom(typeof(IDictionary<dynamic, dynamic>)) 

item is IList<object> 
item is IList<dynamic> 

item.GetType().IsAssignableFrom(typeof(IList<object>)) 
item.GetType().IsAssignableFrom(typeof(IList<dynamic>)) 

Tutto ciò return false!

Quindi, come faccio a determinare che (in questo contesto) l'elemento implementa IDictionary o IList?

+1

Date un'occhiata a questo: [Come determinare se un tipo implementa uno specifico tipo di interfaccia generica] (http://stackoverflow.com/questions/503263/how-to-determine-if-a-type -implements-a-specific-generic-interface-type) – Zbigniew

+0

@DaveZych, Quindi come faccio a rilevare che l'elemento implementa IDictionary o IList con QUALSIASI tipo generico? – series0ne

+0

Si sta utilizzando 'IsAssignableFrom' nel modo sbagliato. Questo è vero: 'typeof (Dizionario ). IsAssignableFrom (nuovo dizionario (). GetType());' – khellang

risposta

8
private void CheckType(object o) 
    { 
     if (o is IDictionary) 
     { 
      Debug.WriteLine("I implement IDictionary"); 
     } 
     else if (o is IList) 
     { 
      Debug.WriteLine("I implement IList"); 
     } 
    } 
+0

+1 per soluzione semplice –

+0

non funziona: nuovo ExpandoObject() è IDictionary restituisce false e ha chiesto se implementa qualsiasi implementazione di IDictionary <,> – elios264

2

È possibile utilizzare i tipi di interfaccia non generici oppure, se è davvero necessario sapere che la raccolta è generica, è possibile utilizzare typeof senza argomenti tipo.

obj.GetType().GetGenericTypeDefinition() == typeof(IList<>) 
obj.GetType().GetGenericTypeDefinition() == typeof(IDictionary<,>) 

Per buona misura, si dovrebbe verificare obj.GetType().IsGenericType per evitare un InvalidOperationException per i tipi non generici.

+0

Perché il downvote? – Jay

+0

'item.GetType() == typeof (IList <>)' è ancora falso, prova questo –

+0

'item is typeof (IList <>)' sintassi sbagliata, compila errore –

1

Non sono sicuro se questo è quello che ci vuole, ma è possibile utilizzare il GetInterfaces sul tipo di elemento e poi vedere se una delle lista restituita sono IDictionary o IList

item.GetType().GetInterfaces().Any(x => x.Name == "IDictionary" || x.Name == "IList") 

Che dovrebbe farlo credo .

Problemi correlati