Given a particular interface ITarget<T> and a particular type myType, here’s how you would determine T if myType implements ITarget<T>. (This code snippet is taken from the answer to an earlier question.)
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(ITarget<>))
return i.GetGenericArguments ()[0] ;
However, this only checks a single type, myType. How would I create a dictionary of all such type parameters, where the key is T and the value is myType? I think it would look something like this:
var searchTarget = typeof(ITarget<>);
var dict = Assembly.GetExecutingAssembly().[???]
.Where(t => t.IsGenericType
&& t.GetGenericTypeDefinition() == searchTarget)
.[???];
What goes in the blanks?
Note that if you have multiple classes implementing
ITarget<>and using the same generic type argument — for example,class Foo : ITarget<string>andclass Bar : ITarget<string>— then theToDictionarycall will fail with anArgumentExceptioncomplaining that you can’t add the same key twice.If you do need a one-to-many mapping then you have a couple of options available.
Use
ToLookuprather thanToDictionaryto generate aLookup<K,V>:If you prefer to work with something like a
Dictionary<K,List<V>>then you could do this: