jeudi 16 avril 2020

Build Type which implements generic type parameter interfaces through Reflection

I have the following structure:

namespace A
{
  abstract public class BaseClass<To, T> { }
}

namespace A.B
{
  interface IFooB { double Prop1 { get; set; } }

  abstract public class BaseSubClassB<T> : A.BaseClass<float, T> { }

  public class SubClassB<T> : BaseSubClassB<T> where T : IFooB { }
}

namespace A.C
{
  interface IFooC { double Prop2 { get; set; } }

  abstract public class BaseSubClassC<T> : A.BaseClass<bool, T> { }

  pubic class SubClassC<T> : BaseSubClassC<T> where T : IFooC { }
}

I also have a method that recursively gives the list of non-abstract generic and non-generic Types that inherit from a base type in the same assembly like so

public static List<Type> GetAllDerivedTypes(Type baseType) { ... };

such that GetAllDerivedTypes(typeof(A.BaseClass<, >)) basically returns

List<Type> allSubClasses = new List<Type> {typeof(A.B.SubclassB<>), typeof(A.C.SubClassC<>)}

Now I would like to create an instance of each of these collected Types in allSubClasses. How I understand it, I would have to do something like the following:

foreach(var type in allSubClasses)
{
  Type constructedType = type.MakeGenericType(new Type[] { typeof(TYPEPARAMETER) });
  var obj = Activator.CreateInstance(constructedType);
}

where TYPEPARAMETER could be a class which provides all the Properties needed in the type parameters of the subclasses in allSubClasses, e.g.

public class TYPEPARAMETER : A.B.IFooB, A.C.IFooC, ...
{
  double Prop1 { get; set; }
  double Prop2 { get; set; }
  ...
}

Would that be a valid approach to create the instances? And if yes, what would be a way to build TYPEPARAMETER at runtime through Reflection which implements all required interfaces and their properties?





Aucun commentaire:

Enregistrer un commentaire