2009-12-14 135 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]; 

的类型将是你所期望的,它是集合中包含的对象的类型,而不是周围的任何泛型类型它。

相关问题