首页 > 解决方案 > 如何获取未知列表类型(列表)

问题描述

我有一个方法可以获取类型为 T“GetPropertiesInfor() where T : new()”的所有属性,但是如果 TI 中有一个列表,则无法在列表中获取 UnknowType 的 PropertyInfor。

为此,我目前正在互联网上寻找解决方案,但我不知道我的搜索关键字是否正确。

这是我的方法:

//Get ProperTyInfor of a type T
    public void GetPropertiesInfor<T>() where T : new()
    {
        T obj = new T();
        List<PropertyInfo> mpropertyInfos = 
        obj.GetType().GetProperties().ToList();
        for (int i=0;i< mpropertyInfos.Count;i++)
        {
            Console.WriteLine("property type ["+ i + "] = " 
             + mpropertyInfos[i].PropertyType);
            //If property i of T is type of List

  if(typeof(IEnumerable).IsAssignableFrom(mpropertyInfos[i].PropertyType)) 
            {
             //now I know this property mpropertyInfos[i] is type of list
             //how can I get PropertyInfor of Items in the list
            }
        }
    }

如果 mpropertyInfos[i] 是一种列表,我想获取列表将存储的项目的所有 PropertyInfor。

标签: c#

解决方案


基本上你需要做的就是type.GetGenericArguments()[0]假设你只有一个参数(就像一个列表一样)

if(typeof(IEnumerable).IsAssignableFrom(mpropertyInfos[i].PropertyType)))
    var genericParam = mpropertyInfos[i].PropertyType.GetGenericArguments()[0];

Type.GetGenericArguments 方法

返回表示封闭泛型类型的类型参数或泛型类型定义的类型参数的 Type 对象数组。


推荐阅读