如何从IQueryable <t>获取T的属性?</t>

时间:2014-08-25 18:09:54

标签: c# reflection

我有一个返回T的IQueryable的方法。使用Reflection我得到的方法的返回类型是T的IQueryable。我想用Reflection来给我T的所有属性,但是当我使用以下代码,没有属性:

        //Get return type of method and then get its Public properties
        var returnType = methodInfo.ReturnType; // returns typeof(IQueryable<T>)
        var returnTypePropertyInfos = returnType.GetProperties();
        var propertySpecs = returnTypePropertyInfos.Select(returnTypePropertyInfo => new VPropertySpec()
        {
            PropertyName = returnTypePropertyInfo.Name, PropertyType = returnTypePropertyInfo.PropertyType.Name
        }).ToList();

2 个答案:

答案 0 :(得分:2)

假设属性类型为IQueryable<T>,您可以这样做:

returnTypePropertyInfo.PropertyType.GetGenericArguments()[0].GetProperties();

答案 1 :(得分:0)

我如何用LINQ完成它:

var propertySpect = 
  from argument in methodInfo.ReturnType.GetGenericArguments()
  from property in argument.GetProperties()
  select new VPropertySpec() {
    PropertyName = property.Name, PropertyType = property.PropertyType.Name,
    // Maybe add for multiple generic arguments: GenericArgument = argument,
  };