是否可以将反射类型列表转换为其原始的强类型对象?

时间:2013-10-13 20:43:13

标签: c# reflection types casting

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

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

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

    return ?;
}

1 个答案:

答案 0 :(得分:1)

这是一个假设所有类型都有默认构造函数的可能实现。

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

我还建议检查类型是否是一个类,而不是抽象的。

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