zoukankan      html  css  js  c++  java
  • 反射遍历List<>泛型类型

    有这样一个需求:一个实体模型,有一个属性是一个实体列表List<OrderDetail>,我需要对实体列表遍历,对每一个实体的属性根据属性特性进行验证,如是否为必填等等,如下一个反射方法能满足需求。

    public class OrderObj
    {
        public Order order {get;set;}
        public List<OrderDetail> orderDetail {get;set;}   
    }
    
    public class Order
    {
        public string OrderID {get;set;}
    }
    
    public class OrderDetail
    {
        [Required]
        public string ID {get;set;}
        [Number]
        public string Quantity {get;set}
    }

    示例代码:

    public void MyMethod(object obj)
    {
        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            object value = propertyInfo.GetValue(obj, null);
            if (propertyInfo.PropertyType.IsGenericType)
            {
                Type objType = value.GetType();
                int count = Convert.ToInt32(objType.GetProperty("Count").GetValue(value, null));
                for (int i = 0; i < count; i++)
                {
                    object listItem = objType.GetProperty("Item").GetValue(value, new object[] { i });
                }
            }
        }
    }
  • 相关阅读:
    ....
    排序相关的问题(jq,java)_1123
    Spring aop 记录操作日志
    vue -element ui 自定义验证规则,封装在公共的文件里
    vue
    ES6 新特性
    正则表达式
    面向对象基础--继承(2)
    面向对象基础(1)
    安装vue环境
  • 原文地址:https://www.cnblogs.com/PongorXi/p/3255612.html
Copyright © 2011-2022 走看看