Has anyone heard of a “type dictionary” that uses types as keys and supports inheritance?
In my application, I would like to have a dictionary from types to functions, sort of like:
Dictionary<Type, Func<object, object>> Transformers;
The idea is that it will be used to transform an object in a certain way depending on its type:
// Transform an object 'obj'
object result = Transformers[obj.GetType()](obj)
A regular dictionary has the disadvantage that the type must match exactly. Therefore, if I wrote a transformer for IList <T>, you should not use it in the Transformers dictionary, because no object has type IList <T> (only T [], List <T>, etc.) In other words if obj is a List <T>, the transformer for IList <T> will not be found by searching in a regular dictionary.
Assuming there is no such thing as TypeDictionary <TValue>, I could write it if it is not too complicated. Any ideas on how to do this?
source
share