C#反射PropertyInfo MVC中的嵌套类

时间:2013-08-02 16:32:59

标签: asp.net-mvc reflection asp.net-mvc-2 .net-3.5 propertyinfo

当深度超过一个级别时,是否存在基于字符串值检索PropertyInfo的通用方法。

我认为这可能很简单,但我的搜索结果仅与我的搜索条件一样好,而且我认为我有一个问题,明确了正确的关键字以获取我所追求的搜索结果。

我希望能够执行以下操作(如果密钥是针对直接属性/一个级别 - 即key ='firstName',则该方法非常有效):

public static PropertyInfo (this HtmlHelper htmlHelper, string key) {

     PropertyInfo pInfo = htmlHelper.ViewData.Model.GetType().GetProperty(key);

     return pInfo;
}

但是我有办法仅根据字符串返回PropertyInfo 当Key等于更复杂的东西时,例如嵌套类,对象,列表等......:

  • key =“somelist [0] .myproperty”
  • key =“Items [0] .someotherlist [1] .someproperty”(其中Items定义为List<Item> Items {get; set;}, someotherlist is defined similarly

该方法是否足够通用,可以根据需要(定义)向下钻取多个级别?

2 个答案:

答案 0 :(得分:1)

所以这就是我想出来的......这就是罗嗦,而且主要是思想的流动&#39;

我有自定义的HtmlHelperExtension,并且在其中:

 PropertyInfo[] pInfoArray = htmlHelper.ViewData.Model.GetType().GetProperties();

 PropertyInfo pInfo = GetPropertyInfo(pInfoArray, key);

这个GetPropertyInfo()方法接受keyPropertyInfo数组遍历属性,直到keypart(使用正则表达式从字符串中删除任何数组的指示,所以我只留下属性)匹配属性名称。在匹配时,确定这是否是循环中的第一个循环,如果是,则将匹配的属性分配给我的Temp TypePropertyInfo变量。如果仍然要循环使用keyParts,则后续循环现在使用先前设置的临时变量和for循环索引[i]来迭代/深入查看类结构。每次设置pInfoTemp变量,然后设置pTypeTemp,以便下一个循环可以使用它停止的位置。

    private static PropertyInfo GetPropertyInfo(PropertyInfo[] pInfoArray, string key)
    {
        PropertyInfo pInfo = null;
        string[] keyParts = key.Split('.');
        Regex arrayRgx = new Regex("\\[\\d*\\]");
        PropertyInfo pInfoTemp = null;
        Type pTypeTemp = null;

        foreach (PropertyInfo prop in pInfoArray)
        {
            string keyPartsTrimmed = arrayRgx.Replace(keyParts[0], ""); // removes '[#]' from string

            if (keyPartsTrimmed == prop.Name)   // match property name
            {

                for (int i = 0; i < keyParts.Count(); i++)
                {
                    if (i == 0) // initial item [0]
                    {
                        pTypeTemp = prop.PropertyType;  // gets [0]'s type
                        pInfoTemp = prop;               // assigns [0]'s property info
                    }
                    else
                    {
                        pInfoTemp = GetNestedPropertyInfo(pTypeTemp, arrayRgx.Replace(keyParts[i], "")); // gets [i]'s property info for return or next iteration
                        pTypeTemp = pInfoTemp.PropertyType; // gets [i]'s type for next iteration
                    }
                }

                pInfo = pInfoTemp;
                break;
            } 
        }

        return pInfo;
    }

前一个方法调用下一个方法来获取嵌套属性信息,更重要的是检测passItemType是否为List(没有这个,它无法正常工作,因为它无法找到List&lt;中要求的属性。 &gt;类型。我需要知道列表项类型是什么。

    private static PropertyInfo GetNestedPropertyInfo(Type passedItemType, string passedProperty)
    {
        PropertyInfo pInfoOut = null;

        if (passedItemType.IsGenericType && passedItemType.GetGenericTypeDefinition() == typeof(List<>))
        {
            Type itemType = passedItemType.GetGenericArguments()[0];
            pInfoOut = itemType.GetProperty(passedProperty);
        }
        else
        {
            pInfoOut = passedItemType.GetProperty(passedProperty);
        }

        return pInfoOut;
    }

这当前符合我的要求,我已经使用以下属性,列表,子类,带列表的子类等进行了测试,深度为4级,但无论深度如何都应该正常运行:

  • 的firstName
  • lastName的
  • 项目[1] .sprocket
  • subClass.subClassInt
  • subClass.mySubClassObj.sprocketObj
  • subClass.ItemsInMySubClass [1] .sprocket
  • subClass.ItemsInMySubClass [0] .mySubClassObj.widgetObj
  • subClass.ItemsInMySubClass [2] .mySubClassObj.sprocketObj

如果有人有更好的解决方案,或者看到我所拥有的任何潜在问题,我欢迎反馈。

答案 1 :(得分:0)

在您的情况下,最好的方法是创建一个解析该表达式的解析器。