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

情到浓时终转凉″ 提交于 2019-12-11 09:16:55

问题


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



来源:https://stackoverflow.com/questions/19350073/is-it-possible-to-cast-a-list-of-reflected-types-to-their-original-strongly-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!