我有很多类都在同一个接口(interface)中,都在同一个程序集中,都符契约(Contract)一个通用接口(interface):
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
可以安全地假设如果我们有一个 IFactory<T>对于特定的 T它是唯一的那种。 (也就是说,没有两个实现 IFactory<Apple> 的东西。)
我想使用反射来获取所有这些类型,然后将它们全部存储在 IDictionary 中,其中键为 typeof(T)值就是对应的IFactory<T> .我想最终我们会得到这样的结果:
_map = new Dictionary<Type, object>();
foreach(Type t in [...]) {
object factoryForType = System.Reflection.[???](t);
_map[t] = factoryForType;
}
最好的方法是什么?我不知道如何用 System.Reflection 做到这一点接口(interface)。
请您参考如下方法:
为了识别作为接口(interface)通用定义的类,我使用了以下扩展方法:
public static class TypeExtensions
{
public static bool IsGenericTypeOf(this Type t, Type genericDefinition)
{
return t.IsGenericType && genericDefinition.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();
}
}
然后您可以使用 Type.GetGenericArguments 方法找到“T”。
这样你最终会得到类似的东西:
var allTypes = ...; // Maybe: Assembly.GetExecutingAssembly().GetTypes()
var dictionary = allTypes.Where(t => t.IsGenericTypeOf(typeof(IFactory<>))).ToDictionary(t => t.GetGenericArguments()[0], t => t);
