如何使用propertyInfo获取列表类型属性的值

时间:2016-02-26 04:33:33

标签: c# reflection asp.net-mvc-5 action-filter

$scope.removeBorder=function(id,index,catvalue){
        $scope.listOfSubCatagory[index]=[];
        rowData['cat']=catvalue;
        var catdata=$.param({'action':'subcat','cat_id':catvalue});
        $http({
            method:'POST',
            url:"php/customerInfo.php",
            data:catdata,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function successCallback(response){
            angular.forEach(response.data,function(obj){
                var data={'name':obj.subcat_name,'value':obj.subcat_id};
                $scope.listOfSubCatagory[index].push(data);
            })
        },function errorCallback(response) {
        })
    }
$scope.saveResturantDetails=function(){

   //here i want to collect data.
}

如何获取列表类型的属性值,我在模型中的属性是示例的列表类型我的模型包含列表属性

            private static void Getproperties(Object Model) {
            Type objType = Model.GetType();
            PropertyInfo[] properties = objType.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object propValue;
                //Checking if property is indexed                 
                if(property.GetIndexParameters().Length ==0)
               propValue  = property.GetValue(Model,null);
                else
                {  
                 // want to retrieve collection stored in property index not passing 0 index returning element at 0 location ,how can i get whole list  
                 propValue = property.GetValue(objectModel,new Object[]{0});                       
                 }
                var elems = propValue as IList;
                 .... }

想要创建一个过滤器并添加到行动中我可以检查潜在的Xss攻击,模型是否包含任何此类攻击

2 个答案:

答案 0 :(得分:3)

第二个参数你真的不需要这个重载。您真正需要的是将object方法返回的.GetValue()转换回List<T>类型。示例:

class MyClass
{
    public List<int> MyProperty { get { return new List<int>() { 3, 4, 5, 6 }; } }
}

class Program
{        
    static void Main()
    {
        MyClass instance = new MyClass();
        PropertyInfo info = instance.GetType().GetProperty("MyProperty");

        List<int> another = info.GetValue(instance) as List<int>;

        for (int i = 0; i < another.Count; i++)
        {
            Console.Write(another[i] + "   ");
        }
    }
}

输出:3 4 5 6

答案 1 :(得分:0)

检查一下。

      List<string> sbColors = new List<string>();
      Type colorType = typeof(System.Drawing.Color);
      PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
      foreach (PropertyInfo c in propInfoList)
      {
         sbColors.Add(c.Name);
      }