簡體   English   中英

如何通過反射獲取集合中包含的類型

[英]How to get the type contained in a collection through reflection

在我的代碼的某些部分,我傳遞了T類型的對象集合。 我不知道我將通過哪個具體的集合,除了它的IEnumerable

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

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

更新 :我應該澄清一下我正在工作的背景(一個Linq提供者)。

我的函數有如下的簽名,我將集合的類型作為參數:

string GetSymbolForType(Type collectionType)
{

}

collectionType有沒有辦法獲取包含的對象類型?

來自Matt Warren的博客

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;
    }
}
myCollection.GetType().GetGenericArguments() 

將返回args類型的數組。

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

會告訴你對象的類型。

然后你應該測試你想要的類型:

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

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

馬特戴維斯釘了它但你需要索引:)

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

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

你不能只使用t.GetType()來做到這一點。

為什么不直接實現IEnumerable<T> 例如:

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

除此之外,您最好使用is.GetType檢查每個單獨對象的類型,而不是嘗試從容器本身處理它。

如果這不是一個選項,你真的需要知道基本容器的類型,你基本上必須檢查使用is看它實現了什么接口(EG: IList<int>等)。 賠率是你的數組的類型將是一個泛型,這意味着嘗試從它的名稱返回到它的數據類型將是非常混亂。

嗯,我在這里很晚,但不應該這樣做:

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

   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM