c# - 具有不同返回类型和参数数量的 Func 委托(delegate)列表

标签 c# delegates

我有一个类,需要在构造函数中传递不同数量的 Func 委托(delegate)。这些委托(delegate)中的每一个都将指向不同的函数,每个函数具有不同的返回类型,并且具有不同数量的参数( double 类型)。然后将相应地调用每个函数。

问题 1. 现在,为了让使用此类的人更轻松,我正在考虑允许用户传递 List<object> Func 委托(delegate)的数量。这是否可能,如果可以,我是否能够确定 List<object> 的方法中每个 Func 所需的返回类型和参数数量。被传递给(即构造函数)?

问题 2. 如果上述方法不可行,我是否需要使用返回类型/参数数量的每种不同组合来重载构造函数,并相应地路由每个 Func -_- ...如果没有,有人可以在正确的方向,我觉得我正在以错误的方式处理这个问题......

注意 - 来自 python 背景,我会做这样的事情(我在 c# 方面缺乏经验):

import inspect
def test(x): return x
inspect.getargspec(test)

returns: ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)

非常感谢

最佳答案

Question 1. Right now, to make things easier for those using this class, I am thinking about allowing the user to pass a List of Func delegates. Is this possible, and if so am I able to determine the return type and number of params required for each Func in the method in which the List is passed to (i.e. the constructor) ?

不是真的。您可以允许 List<Delegate> (或元素类型为 Delegate 的其他集合),但没有 Func -具体,有两个原因:

  • Func实际上是一个类型家族,具有不同数量的泛型类型参数。就 CLR 而言,这些类型是完全独立的; Func<TResult>Func<T, TResult>Action<T> 一样不同和EventHandler .

  • 即使您只处理相同泛型委托(delegate)类型的多个值,它们可能具有不同类型参数的事实意味着它们对于 CLR 来说是不同的类型;没有办法说List<Func<>>对于“具有可能不同类型参数的函数列表”。同样,CLR 将它们视为单独的类型 - 尽管这一次至少有一个具有通用泛型类型定义。

Question 2. If the above is not feasible, will I need to overload the constructor with every different combination of return types/number of params and route each Func accordingly

嗯,有几种选择:

  • 将所有参数设为可选,并为每个参数指定默认值 null ,然后在调用构造函数时使用命名参数:

     var foo = new Foo(clickHandler: () => ...,
                       keyHandler: key => ...);
    
  • 创建一个构建器,以便可以将各种函数设置为属性 - 这与对象初始值设定项语法配合得很好:

     var foo = new Foo.Builder {
                   ClickHandler = () => ...,
                   KeyHandler = () => ...
               }.Build();
    

当然,后两种解决方案都取决于您是否确实具有特定的指定目的。

如果您能更清楚地了解自己想要实现的目标,将会有所帮助 - 正如 dtb 所说,多态性可能更适合这里。您可以创建一个带有虚拟方法的无操作实现的抽象类,并且实现可以选择要覆盖哪些方法。

关于c# - 具有不同返回类型和参数数量的 Func 委托(delegate)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592086/

相关文章:

c# - 刷新窗体上的所有控件

c# - 用于查找 C# 类和方法名称的正则表达式

C#代码重构(lambda表达式)

c# - 委托(delegate) - 方法名称预期错误

c# - 委托(delegate)事件问题

c# - 从返回 403 forbidden 的网站解析

c# - WCF 和 ref 参数

vb.net - 委托(delegate)和 ParamArray - 解决方法建议?

ios - 确定何时将 subview 添加到 tableView

java - Android - 单击按钮时使用 AsyncTask 发送 HTTP 请求 |委托(delegate)问题