2016-02-26 29 views
1
列表類型屬性的值
  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; 
       .... } 

我怎樣才能獲得列表類型的屬性值,我在模型屬性是一個列表類型。例如我的模型包含一個列表屬性如何開始使用的PropertyInfo

List<User> 

想要創建一個過濾器,並添加到,我可以檢查潛在的XSS攻擊行爲,模型中是否包含任何這類攻擊

回答

2

你並不真的需要這種過載與第二個參數。你真正需要的是將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

+0

如果實例和屬性名不知道,我想創造這個作爲通用的基於模型的出了神 –

+0

如果我理解正確的,你想通過反射和投值這種類型擺脫財產牛逼說法。問題是泛型類型參數是在編譯時推斷的。所有使用反射的操作都是實時操作,因此它暗示我們不能使用泛型來處理動態獲取的數據。 – Fabjan

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