简体   繁体   中英

Is it possible to cast a list of reflected Types to their original strongly typed objects?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM