Reputation: 6542
I use reflection on interfaces to determine exactly which methods in an implementing type are from the interface (vs overloads which are not from the interface). This works very well for System assemblies, except for one case: System.Collections.Generic.IDictionary<TKey, TValue>
.
From MSDN I know that IDictionary<TKey, TValue>
implements ICollection<KeyValuePair<TKey, TValue>>
, but I can't find anywhere via reflection where you can find "KeyValuePair" stated. Currently, I'm using some specific logic for IDictionary to work around this problem, but I'd like to be able to treat IDictionary as I do the other interfaces and not have to code directly to this idiosyncrasy.
Here's a code snippet (remember, it virtually always works, except for the generic IDictionary):
foreach (System.Type asmType in SystemAssembly.GetExportedTypes())
{
if (asmType.IsInterface)
{
//is there anything in the System.Type object which will tell me that the interface implements ICollection<KeyValuePair<...>> ?
//at this point, I call 'GetMethods', and for IDictionary methods where I expect a KeyValuePair parameter, I get a System.Object parameter instead
foreach (MethodInfo method in asmType.GetMethods(...binding flags...))
{
ParameterInfo[] parameters = method.GetParameters();
...
}
}
}
Resolution: Lee's answer nailed it - it finally got to where I could see "KeyValuePair" via reflection.
Upvotes: 1
Views: 217
Reputation: 144126
If you have a type instance for the open IDictionary<,>
type you can do something like:
Type dictType = typeof(IDictionary<,>);
var icolIface = dictType.GetInterfaces()
.First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>));
Type colType = icolIface.GetGenericArguments()[0];
Upvotes: 1
Reputation: 69250
This small snippets shows the method calls and properties to use to get the KeyValuePair<TKey, TValue>
type out of the dictionary.
var someDictionary = new Dictionary<int, string>();
var kvType = someDictionary.GetType().GetInterfaces()
.Single(i => i.Name == "ICollection`1")
.GetGenericArguments().Single();
Because I don't know exactly what you are after, I hard coded the selection of the ICollection`1
interface out of the interfaces implemented.
Upvotes: 1