mardi 4 octobre 2016

initialize an IEnumerable property using reflection in c# (propertyInfo)

Assuming a class (could be others)

class Foo()
{
     IEnumerable<int> SomeNumbers { get; set; }
     IEnumerable<string> SomeStrings { get; set; }       
     int[] ArrayOfInt { get; set; }
     List<int> AListOfIntegers { get; set; }
}

And a method

void Initialize(object obj)
{
     var props = obj.getType().GetProperties();
     foreach(var prop in props)
     {
         //Some logic in case property is a single value, this is using:
         //Convert.ChangeType(value, property.PropertyType, null)

         var list = //Do Some Magic
         prop.SetValue(obj, list, null);
     }
}

How to create a list of the right type?

I tried:

var list = property.PropertyType.GetConstructor(new CType[0]).Invoke(new object[0]);

But this don't work since IEnumerable does n't have constructors (it is an interface), but any supertype would be fine here.

var list = Enumerable.Empty<property.PropertyType.MemberType>();

Isn't even legal





Aucun commentaire:

Enregistrer un commentaire