【问题标题】:How to Get the Value of a List Type Property using propertyInfo如何使用 propertyInfo 获取列表类型属性的值
【发布时间】:2023-03-13 14:55:02
【问题描述】:
            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;
                 .... }

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

List<User>

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

【问题讨论】:

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


    【解决方案1】:

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

    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

    【讨论】:

    • 如果实例和属性名称未知,我想根据传递的模型将其创建为通用
    • 如果我理解正确,您想通过反射从属性中获取 T 参数并将值转换为这种类型。问题是泛型类型参数是在编译时推断出来的。所有带有反射的操作都是实时操作,因此这表明我们不能使用泛型来处理动态获取的数据。
    【解决方案2】:

    检查这个。

          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);
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多