Dynamic function mapping

I would like to define the following two functions:

void Map<T>(Func<T, string> mapper); T Call<T>(string value); 

The card must store a function that turns the string into a result of type T, so that when the "Call" function is called with type T and a string, the corresponding function can be viewed and called.

I thought that the card can store the function in a dictionary like Dictionary<Type, Func<object, string>> , and then Call can make the casting the appropriate type, but I can not make it work. Does anyone know how to achieve this?

+4
source share
2 answers

The argument of the first type of Func is the input, the second is the output: Func<in T, out TResult> - so you need Func<string, T> .

(The MSDN link here uses Func<string, string> fair bit, which is annoying.)

In addition, the dictionary cannot use an argument of type T as different for each element of the dictionary. Rather, use the superclass Func<T, TResult> , which is equal to Delegate .

This should work:

  Dictionary<Type, Delegate> dictionary = new Dictionary<Type, Delegate>(); public void Map<T>(Func<string, T> mapper) { dictionary[typeof(T)] = mapper; } public T Call<T>(string value) { var func = dictionary[typeof(T)] as Func<string, T>; return func.Invoke(value); } 
+5
source

You can try and do something like this (there should be a better way, but I don't see it right now):

 Dictinary<Type, object> _funcDict = ...; void Map<T>(Func<T, string>mapper) { _funcDict[typeof(T)] = mapper; } T Call<T>(string value) { var func = (Func<T, string>)_funcDict[typeof(T)] return func(value); } 

What I don't like is the type of the value of the object in the dictionary, but I'm not sure how you can avoid it.

0
source

Source: https://habr.com/ru/post/1387685/


All Articles