使用反射如何在程序集中查找实现通用基类并创建其实例的类

时间:2012-01-05 18:48:53

标签: c#-4.0

我有一个基础演示者课程:

public abstract class PresenterBase<T> where T : IView
{
    //Some code  
}

实现此基础的具体演示者类:

public class RegistrationPresenter : PresenterBase<IRegistration>
{
    //Some Code
}

具体的演示者工厂,用于返回演示者的实例,该实例取决于特定的接口契约:

public class ProductPresenterFactory : PresenterFactoryBase
{
    // Some code
    public override PresenterBase<IView> GetPresenter(IView view, string name = "")
    {
        if (view == null && string.IsNullOrEmpty(name))
            throw new ArgumentNullException();
        return presenter;
    }
} 

我需要实现GetPresenter方法。用户将在上述情况下放置接口契约,例如类型IRegistration。此方法应该找出实现PresenterBase<IRegistration>并返回实例的类。

1 个答案:

答案 0 :(得分:0)

我没有用编译器写这个;我可能犯了一些错误。

首先需要获取presenterbase的类型,然后我们将为实现搜索汇编,然后调用它的构造函数。我会在代码中写出一些假设。

var genericType = typeof (PresenterBase<>).MakeGenericType(new[] { view.GetType() });
var allTypes = GetType().Assembly.GetTypes(); // I assume the class is in the same assembly.
var typeToImplement = allTypes.Single(t => t.IsSubclassOf(genericType)); // I assume there is only one implementation for the given type
var constructorToCall = typeToImplement.GetConstructors().First(); // I assume there is one constructor
var presenter = constructorToCall.Invoke(new object[0]); // I assume there is no parameter