簡體   English   中英

獲取通用列表中的實際T類型<T>

[英]Get actual type of T in a generic List<T>

如何使用反射在運行時獲取通用List中的實際T類型?

這取決於你究竟在問什么:

  • 在泛型類型Blah<T>編寫代碼時,如何獲得反射類型T

    答案: typeof(T)

  • 我有一個對象,其中包含某個類型TList<T> 如何通過反射檢索T型?

    簡答: myList.GetType().GetGenericArguments()[0]

    答案很長:

     var objectType = myList.GetType(); if (!objectType.IsGenericType() || objectType.GetGenericTypeDefinition() != typeof(List<>)) { throw new InvalidOperationException( "Object is not of type List<T> for any T"); } var elementType = objectType.GetGenericArguments()[0]; 

您可以使用Type.GetGenericArguments返回List<T>的類型T.

例如,這將返回作為參數傳遞的任何List<T>的Type:

Type GetListType(object list)
{
    Type type = list.GetType();
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        return type.GetGenericArguments()[0];
    else
        throw new ArgumentException("list is not a List<T>", "list");
}
typeof (T)

要么

typeof (T).UnderlyingSystemType

新的解決方案老問題的dynamic

void Foo(){
   Type type GetTypeT(data as dynamic);
}

private static Type GetTypeT<T>(IEnumerable<T> data)
{
    return typeof(T);
}

暫無
暫無

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

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