c# – 获取泛型抽象类的所有继承类

前端之家收集整理的这篇文章主要介绍了c# – 获取泛型抽象类的所有继承类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一些方法获取继承通用抽象类的所有类,并对每个类执行一个方法.

我一直在关注这个Change parameter type when implementing an abstract method以获得我想要的类实现,类似于:

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()方法.使用非泛型抽象类,我可以使用以下代码段来获取

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>?

编辑:我忘了提.假设有许多类似于A或B的实现,并将随着时间的推移而添加.我希望有一个“优雅”(如果可能的话)解决方案,以后,我只需要处理实现C,D等.

谢谢!

解决方法

实际上,可以通过分解抽象类来获取实例来调用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;

(旧的,破坏的解决方案)

我想我会做这样的事情(未经测试):

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));

这应该涵盖继承层次结构中的任何内容,利用AbstractRequest上的类型约束.

原文链接:https://www.f2er.com/csharp/100299.html

猜你在找的C#相关文章