How do I put all the types matching a particular C# interface in an IDictionary?
Posted
by Kevin Brassen
on Stack Overflow
See other posts from Stack Overflow
or by Kevin Brassen
Published on 2010-05-19T16:15:33Z
Indexed on
2010/05/19
17:00 UTC
Read the original article
Hit count: 225
I have a number of classes all in the same interface, all in the same assembly, all conforming to the same generic interface:
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
It's safe to assume that if we have an IFactory<T>
for a particular T
that it's the only one of that kind. (That is, there aren't two things that implement IFactory<Apple>
.)
I'd like to use reflection to get all these types, and then store them all in an IDictionary, where the key is typeof(T)
and the value is the corresponding IFactory<T>
. I imagine eventually we would wind up with something like this:
_map = new Dictionary<Type, object>();
foreach(Type t in [...]) {
object factoryForType = System.Reflection.[???](t);
_map[t] = factoryForType;
}
What's the best way to do that? I'm having trouble seeing how I'd do that with the System.Reflection
interfaces.
© Stack Overflow or respective owner