我正在尝试动态创建一个从泛型继承的类型的实例interface。
例如,我有以下基本接口,其中其他几个接口源自:
public interface IDummy { }
我有两个派生接口:
public interface IDummyDerived<T> : IDummy
{
void Foo(T value);
}
public interface ITempDerived<T> : IDummy
{
void HelloWorld(T value);
}
现在我需要一个 ServiceProvider-Class,我可以在其中创建找到实现给定接口的类。每个接口(IDummyDerived 和 ITempDerived)只实现一次。
我的方法是:
internal class DummyServiceProvider
{
public T GetDummy<T>() where T : IDummy
{
Type baseType = typeof(IDummy);
Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(p => baseType.IsAssignableFrom(p) && p.IsClass).ToArray();
//now I have all classes which implements one of my interfaces
foreach(Type type in types)
{
// here I want to check if the current type is typeof(T)
// (typeof(T) == type) -> doesn't work
// (type.GetGenericTypeDefinition() == type) doesnt work
}
}
return default(T);
}
如何正确比较给定typeof(T)的类型与类型数组中的类型?
- 更新:
DummyServiceProvider 的用法如下所示:
IDummyDerived<string> dummyDerived = myDummyServiceProvider.GetDummy<IDummyDerived<string>>()
相关分类