【发布时间】:2018-11-08 01:14:57
【问题描述】:
我正在尝试动态创建一个继承自泛型 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>>()
【问题讨论】:
-
我看到了
IDummyDerived<T>的定义,但没有看到IDummyDerived的定义。如果没有IDummyDerived的定义,代码将无法编译并且应该将编译错误抛出为Using the generic type 'IDummyDerived<T>' requires 1 type arguments。您的问题是否缺少一些代码? -
抱歉,在调用服务提供者时忘记了泛型
-
请查看发布的答案。
标签: c# reflection types