Generic list of actions/funcs

本秂侑毒 提交于 2021-02-10 04:09:21

问题


I'm wondering if its possible to create some kind of generic list of actions/funcs, each with different in/out params.

The reason I need this is I have an executer who's job is getting data from an API, each of the methods in that executer goes to a different path in that API, and I want to be able to schedule those requests so I won't overload that API (they will just block me if I pass their threshold of requests).

So each time a method in that executer is called, I will add that method and its params to a list, and another thread will run over the list and execute methods from there using some timeout.

I have to have this logic in the executer and not from it's caller.

So basically wondering if I can do something like:

List<Func<T,T>> scheduler;

Without declaring the types on creation but instead add different types during runtime.

If there is a better solution or pattern for this please do enlighten me.

[edit] obviously I don't want to implement something like:

Func<List<object>, object> scheduler

回答1:


You can make a List<Tuple<Type, Delegate>> to store your functions.

The below code runs fine:

var scheduler = new List<Tuple<Type, Delegate>>();

scheduler.Add(
    Tuple.Create<Type, Delegate>(
        typeof(Func<int, int>),
        (Func<int, int>)(n => n + 1)));

scheduler.Add(
    Tuple.Create<Type, Delegate>(
        typeof(Func<string, string, int>),
        (Func<string, string, int>)((x, y) => x.Length + y.Length)));

You would then need to use reflection to bring them back from being a Delegate.

This would be a good starting point.




回答2:


If you know the parameter values at the time of adding the func to the list, you can simply capture them in a lambda that applies the Func<T, X, Y, Z ...> and thus reduce it to a Func<T>, e.g.

Func<T, X> funcToAdd = ...
Func<T> wrapper = () => funcToAdd(valueForX);
myFuncList.Add(wrapper);

The type of the func list can then just be List<Func<T>>



来源:https://stackoverflow.com/questions/32033288/generic-list-of-actions-funcs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!