mercredi 23 mars 2016

Add an anonymous subclass object to a base class list

I have a base class (Baseclass) from which I derived some subclasses (Subclass1, Subclass2, etc.). For each subclass, I want:

  • call the constructor with 'fixed' arguments (arg1, arg2, etc.);
  • check if the instantiation is valid (supposing to have a common method IsValid); and
  • add the instantiation to a list of object.

Here follows the excerpt of the code:

subclassList = new List<Type>()
{
   typeof(Subclass1),
   typeof(Subclass1),
   ...
};
List<Baseclass> objectList = new List<Baseclass>();
foreach (Type subclass in subclassList)
{
   ConstructorInfo[] constructorArray = subclass.GetConstructors(BindingFlags.Public);
   object o = constructorArray[0].Invoke(new object[] { arg1, arg2, ... });
   if (((Baseclass)o).IsValid)
   {
      objectList.Add(Convert.ChangeType(o, subclass));
   }
}





Aucun commentaire:

Enregistrer un commentaire