如何获取未知列表类型(List <unknowtype>)中的项的PropertyInfor

时间:2019-01-24 04:37:01

标签: c#

我有一个方法将获取类型T为“ GetPropertiesInfor()的所有Property,其中T:new()”,但是如果T中存在一个列表,则无法在列表中获取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。

1 个答案:

答案 0 :(得分:0)

基本上,您需要做的只是type.GetGenericArguments()[0],前提是您只有一个参数(就像列表一样)

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

Type.GetGenericArguments Method

  

返回一个Type对象数组,这些对象代表以下对象的类型参数   封闭的通用类型或通用类型的类型参数   定义。