dimanche 12 janvier 2020

Set property on a derived class of List

I am using reflection to instantiate a custom class `class MyList : MyBaseClass, IList´:

foreach (FieldInfo field in this.GetType().GetFields())
{
   if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(MyList<>))
   {
      var elementType = field.FieldType.GetGenericArguments()[0];
      var listType = typeof(MyList<>).MakeGenericType(elementType);
      var valueToSet= Activator.CreateInstance(listType);
      field.SetValue(this, valueToSet);
      ...
      valueToSet.MyName = field.Name; // does not work because "valueToSet" does not recognize this property
      ...
   }
}

The problem is, that the part valueToSet.MyName = field.Name does not recognize the property MyName that my custom class MyList<T> has. I also tried defining my MyList<T> as class MyList<dynamic> : MyBaseClass, IList<dynamic> but the valueToSet.MyName = field.Name part throws now the error System.ArgumentException HResult=0x80070057 Message=Object of type objects.MyList 1[System.Object] cannot be converted to type objects.MyList 1[MyNameSpace.MyObjectType1]...

Any hint on how to resolve this? I would like to keep my original declaration without dynamics
Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire