用于从基类实例化派生类的泛型工厂方法 [英] Generic Factory method to instantiate a derived class from the base class

查看:57
本文介绍了用于从基类实例化派生类的泛型工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个工厂方法,该方法使用泛型抽象类型参数通过反射返回具体派生类型的实例.例如.

I am in the process of creating a factory method which uses a generic abstract type parameter to return the instance of the concrete derived type using reflection. For eg.

public abstract class ServiceClientBase : IServiceClient
{
}

public abstract class Channel : ServiceClientBase
{
}

public class ChannelImpl : Channel
{
}

public class ServiceClientFactory
{
    public T GetService<T>() where T : class, IServiceClient
    {
        // Use reflection to create the derived type instance
        T instance = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, null).Invoke(new object[] { endPointUrl }) as T;
    }
}

用法:

Channel channelService = factory.GetService<Channel>();

问题在于,我无法为工厂方法找到任何优雅的方法来实例化在方法中传递给抽象基本类型的派生类型.我唯一能想到的就是维护一个Dictionary,其中包含抽象基和对应的派生类之间的映射,但是在我看来,这就像代码的味道.有人可以提出更好的解决方案吗?

The issue is that I cannot figure out any elegant way for the factory method to instantiate the derived type being passed the abstract base type in the method. The only thing I can come up with is to maintain a Dictionary containing the map between the abstract base and the corresponding derived class but this seems to me like a code smell. Can anybody suggest a better solution.

推荐答案

尽管您有信心只有一个实现,并且假设它在同一程序集中,则可以通过反射找到它.例如:

While you're confident of there being only one implementation, and assuming it's within the same assembly, you could find it via reflection. For example:

Type implementationType = typeof(T).Assembly.GetTypes()
                                   .Where(t => t.IsSubclassOf(typeof(T))
                                   .Single();
return (T) Activator.CreateInstance(implementationType);

当然,出于性能原因,您可能希望拥有抽象类型到具体类型的缓存.

Of course for performance reasons you may well want to have a cache of abstract type to concrete type.

如果有多个实现类,则需要考虑一种替代方法-一个可行的选择是抽象类上的一个属性,说明要使用哪种实现(如果可行).(很难在没有更多上下文的情况下给出好的选择.)

If there are multiple implementation classes, you'll need to think of an alternative - one option would be an attribute on the abstract class saying which implementation to use, if that's feasible. (It's hard to give good options without more context.)

这篇关于用于从基类实例化派生类的泛型工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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