How make Dictionary with lambda functions, with di

2019-09-20 10:19发布

问题:

How make Dictionary with lambda functions, that Func<> contains different numbers of parameters?

Dictionary<string, Func<T, double>> operationsList 
  = new Dictionary<string, Func<T, double>>();

It mast be so?

回答1:

You can make your dictionary type Delegate, but I'm pretty sure that calling Func<> stored this way will be a pain:

var dict = new Dictionary<int, Delegate>();
dict.Add(1, (Func<int, int>)((int x) => x * 10));
dict.Add(2, (Func<int>)(() => 10));

Calling:

var result1 = dict[1].DynamicInvoke(10);
var result2 = dict[2].DynamicInvoke();