简体   繁体   中英

How to Get the Value of a List Type Property using propertyInfo

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

How can i get the Property Value of List Type, my property in the Model is a List Type for Example my Model contains a List Property

List<User>

wants to create a Filter and add to action on which i can check for potential Xss Attack ,whether model contains any such attack

You don't really need this overload with second parameter. What you really need is to cast object returned by .GetValue() method back to type List<T> . Example :

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] + "   ");
        }
    }
}

Output : 3 4 5 6

Check this one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM