gpt4 book ai didi

c# - 如何将带有某些绑定(bind)参数的任意函数传递给另一个函数?

转载 作者:行者123 更新时间:2023-11-30 17:54:43 36 4
gpt4 key购买 nike

我有一个通用函数 CallLater,它应该接受任意其他函数,并可能稍后使用一些参数调用它。应支持所有类型的功能 - 静态、实例、私有(private)、公共(public)。在 CallLater 中借助反射动态分析和构造参数。但是,在将函数传递给 CallLater 之前,其中一些可能需要绑定(bind)到固定值。

例如:

void CallLater(Delegate d) {
// Expects a function that returns string and has one argument of arbitrary type.
if (d.Method.GetParameters().Length == 1 &&
d.Method.ReturnType == typeof(string)) {
object param1 = Activator.CreateInstance(d.Method.GetParameters()[0].ParameterType);
Console.WriteLine((string)d.DynamicInvoke(param1));
}
}

// Has one extra float parameter.
string MyFunc(int a, float b) { ... }

我的想法是做类似的事情:

float pi = 3.14f;
CallLater(delegate(int a) { return MyFunc(a, pi); });

但这并不像编译器提示的那样工作:

Error CS1660: Cannot convert `anonymous method' to non-delegate type `System.Delegate' (CS1660) (test-delegate)

实现我的目标的正确方法是什么?

附言请不要提供声明固定委托(delegate)类型的解决方案,因为 CallLater 更复杂并且可能也支持可变数量的参数。

附言可能是我的解决方案是 Func,但到目前为止我无法在 Mono 上使用它。

最佳答案

您始终可以自己重新声明 Func:

public delegate TReturn FFunc<TArg,TReturn>(TArg arg);

你可以这样使用:

float pi = 3.14f;
CallLater((FFunc<int,string>)(delegate(int a) { return MyFunc(a, pi); }));

关于c# - 如何将带有某些绑定(bind)参数的任意函数传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15794269/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com