mercredi 9 janvier 2019

Reflection, how to get the PropertyType value and convert to IEnumerable

In my solution, I have a business validation service that can be applied on any class with a base class of Entity type.

Now I need to aggregate the rules that are broken but am stuck, I have properties that can be Collections, so i need to check each item in the collection as well.

To do that I have this check

typeof(IEnumerable).IsAssignableFrom(property.PropertyType)

but now that i know that the type is a collection. How do I cast to that Type IEnumerable so that i can proceed with the next step.

This should take as 1st parameter the item from the collection detected.

Something like this

foreach(var collectionItem in collection) { AggregateBrokenRules(collectionItem, ref rules); }

Where collection is the result of the convertion or cast

private void AggregateBrokenRules(Type reflectedType, ref List<BrokenRule> rules)
{
      /// => don't apply any filter of any kind except for what already is provided 
      PropertyInfo[] properties = reflectedType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

      /// => iterate through discovered properties
      foreach (PropertyInfo property in properties)
      {
         /// => if type is IEnumerable
         if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
         {
             /// => cast to IEnumerable 
             var propertyVal = Convert.ChangeType(types, property.PropertyType);


             AggregateBrokenRules(property.PropertyType, ref rules);
          }

          /// => only properties that are of type Entity
          if (typeof(Entity).GetTypeInfo().IsAssignableFrom(property.PropertyType))
          {
              /// => check next level
              AggregateBrokenRules(property.PropertyType, ref rules);
          }

           /// => get the value from this property
           object propertyValue = property.GetValue(reflectedType);
        }
}





Aucun commentaire:

Enregistrer un commentaire