反射遍歷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 });
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM