2017-05-17 4 views
0

Beispielcode:überprüfen Sie, ob Objekt ein System.Generic.List <T>, für jeden T

using System.Collections.Generic; 
    ... 

     // could return anything. 
     private object GetObject(int code) 
     { 
      object obj = null; 

      if (code == 10) 
      { 
       var list1 = new List<Tuple<int, string>>(); 
       list1.Add(new Tuple<int, string>(2, "blah")); 
       obj = list1;     
      } 
      else if (code == 20) 
      { 
       obj = "hello"; 
      } 
      else if (code == 30) 
      { 
       var list2 = new List<string>(); 
       list2.Add("o"); 
       obj = list2; 
      } 
      // else etc, etc. 

      return obj; 
    } 

    private bool DoAction(int code) 
    { 
     object obj = GetObject(code); 

     bool isListT = ??? 
     return isListT;  
    } 

In obigem Code GetObject jede Art von Objekt zurückkehren konnte. Innerhalb von DoAction, nach dem Aufruf von GetObject, möchte ich in der Lage sein zu sagen, ob das zurückgegebene Obj eine Art von System.Collections.Generic.List<T> ist. Es ist mir egal (und kann es auch nicht wissen), was T ist. DoAction (10) und DoAction (30) sollten also true zurückgeben, und DoAction (20) würde false zurückgeben.

+0

Es funktioniert, wenn Sie tun, wenn (yourVar Liste ist ) –

+0

@Arthur: Das wird nicht funktionieren. Vielleicht wäre '(obj is IList)' genug. – Groo

+0

@Achilles: 'System.Object' implementiert 'IEnumerable' nicht. – Groo

Antwort

5

Sie können Type.GetGenericTypeDefinition

object obj = GetObject(code); 
bool isList = obj?.GetType().GetGenericTypeDefinition() == typeof(List<>); 
+0

danke. In C# 4.5 ging ich für: obj! = Null && obj.GetType(). IsGenericType && obj.GetType(). GetGenericTypeDefinition() == typeof (Liste <>) –

1

private static bool DoAction(int code) 
{ 
    object obj = GetObject(code); 

    return obj is IList; 
} 

arbeiten Dann Dies sollte:

var first = DoAction(10); //true 
var second = DoAction(20); //false 
var third = DoAction(30); //true 
Verwandte Themen