Here’s the context:
We have a base class called Body, and many other classes that are inherited from the base class Body.
public class Body{
//...
}
public class A : Body {
//...
}
public class B : Body {
//...
}
// and so on
And there is a service that has a Generic method like this:
public class TheService : ITheService
{
public void Receive<T>(T firstInput, bool secondOne) where T : Body
{
DoingStuff();
}
}
And here is the deal, for all the classes that are derived from the base class Body, we must call the Receive function, so we are doing this:
// Getting all types that are inherited from the Body in the solution
var bodyTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(domainAssembly => domainAssembly.GetExportedTypes()).Where(type => typeof(Body).IsAssignableFrom(type)).ToArray();
// Get the Receive method
var theService = ServiceLocator.Current.GetInstance<ITheService>();
var receive = typeof(ITheService).GetMethod("Receive");
// And finally calling the Receive function for all types
foreach (var bodyType in bodyTypes)
{
var method = receive.MakeGenericMethod(bodyType);
method.Invoke(theService, new object[] { firstInput, secondOne });
}
It works literally fine.
The problem here is :
If the derived classes are generic themselves, it’ll be encountered this error: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true
public class C<T> : Body where T : class {
//...
}
The foreach code block is ok with classes A and B but it will throw an exception with that error message when it reaches C.
Does anyone have any idea how to solve the problem?