是否可以将反射类型的列表转换为其原始强类型对象? [英] Is it possible to cast a list of reflected Types to their original strongly typed objects?

查看:217
本文介绍了是否可以将反射类型的列表转换为其原始强类型对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下面的代码的第二行,我检索一个类型列表。我想将此作为IBusinessObject的列表返回。这可能吗?如果是这样,我该怎么做呢?

From the second line of the code below, I retrieve a List of Types. I would like to return this as a list of IBusinessObject. Is this possible? And if so, how would I go about doing this?

public List<IBusinessObject> RetrieveAllBusinessObjects()
{
    var businessObjectType= typeof(IBusinessObject);

    List<Type> implementationsOfBusinessObject = AppDomain.CurrentDomain.GetAssemblies()
         .SelectMany(s => s.GetTypes())
         .Where(businessObjectType.IsAssignableFrom).ToList();

    return ?;
}


推荐答案

所有类型都有一个默认的构造函数。

Here a possible implementation that assumes that all the types have a default constructor.

public List<IBusinessObject> RetrieveAllBusinessObjects()
{
    var businessObjectType= typeof(IBusinessObject);

    List<Type> implementationsOfBusinessObject = AppDomain.CurrentDomain.GetAssemblies()
         .SelectMany(s => s.GetTypes())
         .Where(businessObjectType.IsAssignableFrom).ToList();

    return implementationsOfBusinessObject.Select(t => (IBusinessObject)Activator.CreateInstance(t)).ToList();
}

我还建议检查类型是否是一个类,

I also suggest to check if the type is a class and is not abstract.

通常在处理这样的场景时,最好使用依赖注入容器来解析所有的依赖。例如,Castle Windsor是一个类型化的工厂设施,您可以使用它来解析实现特定接口的所有实例。查看 http://docs.castleproject.org/Windsor .Typed-Factory-Facility-interface-based-factories.ashx http:// docs.castleproject.org/Windsor.Resolvers.ashx

Usually when dealing with scenario like this it is better to use dependency injection container that can resolve all your dependencies. For example Castle Windsor as a typed factory facility that you can use to resolve all the instance that implement a specific interface. Look at http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx and http://docs.castleproject.org/Windsor.Resolvers.ashx

这篇关于是否可以将反射类型的列表转换为其原始强类型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆