I've got a generic method:
Func<IEnumerable<T>, bool> CreateFunction<T>()
where T
can be any number of different types. This method does a bunch of stuff using reflection and if T
is an IDictionary
, regardless of the the dictionary's TKey
and TValue
I need to execute dictionary specific code.
So the method could be called:
var f = CreateFunction<string>();
var f0 = CreateFunction<SomePocoType>();
var f1 = CreateFunction<IDictionary<string,object>>();
var f2 = CreateFunction<Dictionary<string,object>>();
var f3 = CreateFunction<SomeDerivedDictionaryType<string,object>>();
etc.
Clarification per @Andy's answer
Ultimately I want to know if T
inherits from/implements IDictionary
even if T
itself is Dictionary
or some other type that derives from that interface.
if(typeof(T) == typeof(IDictionary<,>)
doesn't work because T
is the generic type not the generic type definition.
And without knowing TKey
and TValue
(which are not known at compile time) I can't do a comparison to any concrete type that I would know about until runtime.
The only thing that I've come up with are looking at the type's name or inspecting its method with reflection, looking for methods that would lead me to believe it is a dictionary (i.e. look for ContainsKey
and get_Item
).
Is there any straightforward way to make this sort of determination?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…