Test whether an object implements a generic interf

2020-04-05 16:51发布

I want to test an object to see if it implements IDictionary<TKey,TValue> but I don't care what TKey and TValue are.

I can test if is a concrete instance of the framework Dictionary<,> like this:

bool isDict = type.IsGenericType && 
    (typeof(Dictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition());

but I can't think of a way to test for something that implements IDictionary<,>. This technique doesn't work for the interface; IsAssignableFrom return false if I test against the generic base type IDictionary<,>, which seems odd since it works for the concrete type.

Normally you would use is to test if something implements an interface, but of course this only works if I want to test for a specific generic interface. Or I would just test for a common ancestral interface, but unlike other generic data structures such as IList<> and ICollection<>, there is no unique non-generic interface from which the generic IDictionary<TKey,TValue> inherits.

1条回答
甜甜的少女心
2楼-- · 2020-04-05 17:34

How about something like

return type.GetInterfaces()
           .Where(t => t.IsGenericType)
           .Select(t => t.GetGenericTypeDefinition())
           .Any(t => t.Equals(typeof(IDictionary<,>)));

which I'm sure that you can easily generalize for any generic type definition.

查看更多
登录 后发表回答