【发布时间】:2023-03-29 16:50:01
【问题描述】:
假设我有这个类:
public class Function {
public int argc; //number of arguments of the function
public float[] argv;
public Func<float> f; //attribute to store a function (e.g. Sin(x) or Pow(a, b))
}
我想创建具有不同功能的Function 实例,例如Sin(x) 或Pow(a, b),但我不知道如何将现有函数(带有任意数量的参数)绑定到Func .显然它的声明并不总是Func<float>,而是Func<float, float>、Func<float, float, float>等。
我一直在寻找Func、delegate、Action,但仍然没有弄清楚如何拥有这个可以容纳和执行具有不同数量参数的函数的“函数胶囊”。为简单起见,我认为唯一的输入和输出类型是float。
我正在考虑使用 Func<List<float>> 之类的东西,但我想知道是否有更好的选择。
【问题讨论】:
-
好吧,
Func<float>只是返回一个浮点数。看起来您的Function实例将存储参数列表.. 那么为什么不使用无参数委托(您拥有;Func<float>)并在其闭包中使用argv? -
即:
this.f = delegate() { return Math.Pow(this.argv[0], this.argv[1])}; -
它给了我一个错误
this.f is a type but it's used as a variable。我将f声明为public delegate float f();,并在构造函数中编写了与您发送的代码相同的代码。 -
对不起,试试这个。我错过了一个分号和一个演员表:
this.f = delegate() { return (float)Math.Pow(this.argv[0], this.argv[1]);};(REPL) -
将
f保留为public Func<float> f;