I would like to define the following two functions:
void Map<T>(Func<T, string> mapper);
T Call<T>(string value);
Map needs to store the function that turns a string into a result of type T so that when the “Call” function is called with a type T and a string the appropriate function can be looked up and called.
I was thinking that map could store the function in a dictionary of type Dictionary<Type, Func<object, string>> and then Call could do the casting to the appropriate type but I’m unable to get that to work. Does anyone know how to achieve this?
The first type argument of
Funcis the input, the second the output:Func<in T, out TResult>— so you needFunc<string, T>.(The MSDN reference here uses
Func<string, string>a fair bit which is annoying.)Also, the dictionary can’t use the type argument
Tas that’s different for each element in the dictionary. Rather, use the superclass ofFunc<T, TResult>which isDelegate.This should work: