2009-12-14 126 views
7

在我的代碼的某些部分中,我傳遞了一組類型爲T的對象集合。我不知道我會通過哪些具體收集,除了阻止IEnumerable如何通過反射獲取集合中包含的類型

在運行時,我需要找出哪種類型的T是(例如System.Double,System.String等)。

有什麼方法可以找到它嗎?

更新:也許我應該更清楚一點,我在(一個LINQ提供程序)工作的背景。

我的功能有類似下面的簽名,在這裏我得到了集合的類型作爲參數:

string GetSymbolForType(Type collectionType) 
{ 

} 

有來自collectionType任何方式來獲得所包含的對象類型?

+1

從集合類型中,您只能獲得泛型集合中包含對象的類型。如果你使用經典集合,除了迭代對象並專門詢問它們的類型之外,你將不會有很好的機會。 – 2009-12-14 11:43:14

回答

14

Matt Warren's Blog

internal static class TypeSystem { 
    internal static Type GetElementType(Type seqType) { 
     Type ienum = FindIEnumerable(seqType); 
     if (ienum == null) return seqType; 
     return ienum.GetGenericArguments()[0]; 
    } 
    private static Type FindIEnumerable(Type seqType) { 
     if (seqType == null || seqType == typeof(string)) 
      return null; 
     if (seqType.IsArray) 
      return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); 
     if (seqType.IsGenericType) { 
      foreach (Type arg in seqType.GetGenericArguments()) { 
       Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); 
       if (ienum.IsAssignableFrom(seqType)) { 
        return ienum; 
       } 
      } 
     } 
     Type[] ifaces = seqType.GetInterfaces(); 
     if (ifaces != null && ifaces.Length > 0) { 
      foreach (Type iface in ifaces) { 
       Type ienum = FindIEnumerable(iface); 
       if (ienum != null) return ienum; 
      } 
     } 
     if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { 
      return FindIEnumerable(seqType.BaseType); 
     } 
     return null; 
    } 
} 
+1

這個伎倆。謝謝。 – 2009-12-14 11:59:31

0
Type t = null 
foreach(object o in list) 
{ 
o.GetType(); 
} 

會得到你的對象的類型。

那麼你也許應該測試所需類型:

if(t == typeof(myClass)) 
{ 
dosomething(); 
} 
else if (t == typeof(myOtherClass)) 
{ 
dosomethingelse(); 
} 
0

廣東話你只是用t.GetType()來做到這一點。

0

爲什麼不直接實施IEnumerable<T>呢? EG:

public void MyFunc<T>(IEnumerable<T> objects)

除此之外,你會更好使用檢查或is.GetType,而不是試圖從容器本身做出來的各個對象的類型。

如果這不是一個選項,但是,你真的需要知道基本的容器的類型你基本上都使用is,看看它的接口實現(EG:IList<int>等)進行檢查。機率是你的數組的類型將是一個通用的,這意味着試圖從它的名稱回到它的數據類型將是相當混亂。

8
myCollection.GetType().GetGenericArguments() 

將返回一個類型爲args的數組。

+4

只適用於泛型類型。 – 2009-12-14 11:41:32

0

好吧,我的方式方法下旬在這裏,但不應該這樣工作:

public static bool ThatCollectionIsOfType<T>(IEnumerable<T> collection, Type got) 
    { 
     if (**typeof(T)** == got) //this line should be good to go... 
     { 
      return true; 
     } 

    } 
0

我使用動態了很多,這是一個問題不時。

馬特·戴維斯釘,但你需要的指數:)

public static void PopulateChildCollection<T>(T currentObject, string singlePropertyName) 
{ 
    dynamic currentObjectCollection = ReflectionTools.GetPropertyValue(currentObject, singlePropertyName); 
    Type collectionType = currentObjectCollection.GetType().GetGenericArguments()[0]; 

的類型將是你所期望的,它是集合中包含的對象的類型,而不是周圍的任何泛型類型它。

相關問題