I am looking for a way to get all classes that inherit from a common abstract class and execute a method for each of these classes.
I followed the Change parameter type when implementing an abstract method to have class implementations that I want, something similar to this:
public abstract class AbstractRequest<TResponseData> where TResponseData : IResponseData { public abstract void Search(); public abstract GoodData BindData(TResponseData data); } public interface IResponseData { } public class AResponse : IResponseData { } public class BResponse : IResponseData { } public class A : AbstractRequest<AResponse> { public override void Search() {
This is a working find, until I need to get all classes A and B and call the Search() method for each of the classes. With a nonequivalent abstract class, I could use the following snippet to get classes
var instances = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(AbstractRequest)) && t.GetConstructor(Type.EmptyTypes) != null select Activator.CreateInstance(t) as AbstractRequest;
Then, how can I get all classes A and B that inherit from AbstractRequest<AResponse> and AbstractRequest<BResponse> ?
Edit: I forgot to mention. Suppose there will be many implementations like A or B and will be added over time. I would like to have an “elegant” (if possible) solution, so later, I only need to take care of the implementation of C, D, etc.
Thanks!
inheritance c # abstract
Ngoc pham
source share