我正在寻找一些方法来获取继承通用抽象类的所有类,并对每个类执行一个方法.
我一直在关注这个Change parameter type when implementing an abstract method以获得我想要的类实现,类似于:@H_502_3@
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() { // get AResponse // Call to BindData() with AResponse } public override GoodData BindData(AResponse data) { // Bind the data from AResponse to GoodData } } public class B : AbstractRequest<BResponse> { public override void Search() { // Get BResponse // Call to BindData() with BResponse } public override GoodData BindData(BResponse data) { // Bind the data from BResponse to GoodData } }
这是有用的,直到我需要得到所有的A& B类并为每个类调用Search()方法.使用非泛型抽象类,我可以使用以下代码段来获取类@H_502_3@
var instances = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(AbstractRequest)) && t.GetConstructor(Type.EmptyTypes) != null select Activator.CreateInstance(t) as AbstractRequest;
然后,我怎样才能获得从AbstractRequest< AResponse>继承的所有类A和B?和AbstractRequest< BResponse>?@H_502_3@
编辑:我忘了提.假设有许多类似于A或B的实现,并将随着时间的推移而添加.我希望有一个“优雅”(如果可能的话)解决方案,以后,我只需要处理实现C,D等.@H_502_3@
谢谢!@H_502_3@
解决方法
实际上,可以通过分解抽象类来获取实例来调用Search()(并且只搜索):
public abstract class AbstractRequest { public abstract void Search(); } public abstract class AbstractRequest<TResponseData> : AbstractRequest where TResponseData : IResponseData { public abstract GoodData BindData(TResponseData data); }
var instances = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && typeof(AbstractRequest).IsAssignableFrom(t) && t.GetConstructor(Type.EmptyTypes) != null select Activator.CreateInstance(t) as AbstractRequest;
我想我会做这样的事情(未经测试):@H_502_3@
var abstractRequestTypes = (from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && typeof(IResponseData).IsAssignableFrom(t) select typeof(AbstractRequest<>).MakeGenericType(t)).ToList(); var instanceTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && abstractRequestTypes.Any(dt => dt.IsAssignableFrom(t));