动作/功能的通用列表 [英] Generic list of actions/funcs

查看:48
本文介绍了动作/功能的通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能创建某种通用的动作/功能列表,每个动作/功能具有不同的输入/输出参数.

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

我需要这个的原因是我有一个执行者,他的工作是从API获取数据,该执行者中的每个方法都转到该API中的不同路径,并且我希望能够安排这些请求,所以我不会超载该API(如果我超过了他们的请求阈值,它们只会阻止我).

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

推荐答案

您可以创建 List< Tuple< Type,Delegate>> 来存储函数.

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

下面的代码运行正常:

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)));

然后,您需要使用反射将它们从 Delegate 撤回.

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

这将是一个很好的起点.

This would be a good starting point.

这篇关于动作/功能的通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆