Is it possible to cast a list of reflected Types t

2019-07-27 11:03发布

问题:

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

回答1:

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.

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