gpt4 book ai didi

f# - 将 c# 委托(delegate)与 f# 函数一起使用

转载 作者:行者123 更新时间:2023-12-04 14:17:20 26 4
gpt4 key购买 nike

我正在尝试从 f# 调用 c# 函数,其中 c# 函数将函数(委托(delegate)?)作为参数,我需要这个参数是 f# 函数。例如:

示例 C#

public static void function_1(double x, ref double y)
{
y = Math.Exp(x);
}

main()
{
state s;
call_func(s, function_1)
}

所以, call_func有一个类型为 void fn(double, ref double) 的参数

在 f# 中,我尝试过:

let function_1 (x:double) (y:double byref) = 
let y = 6.0
()

let test =
let s = new state
let ret = call_func(s, function_1)

但我得到 f# function_1 的错误有类型 double -> double byref -> unit什么时候应该是委托(delegate)的类型 void fn(double, ref double) .

我可以转换类型或类似的东西吗?还是有错误?

最佳答案

如果要从 F# 中的函数创建委托(delegate),可以使用 new运算符并将函数作为参数提供:

let function_1 (x:double) (y:double) = 
()

Program.call_func(s, new Action<double, double>(function_1))

但是,对于 some reason , 如果尝试对包含 ref 的委托(delegate)使用相同的方法,你得到这个错误:

This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking 2 arguments.



因此,如果您遵循错误消息给出的建议,您可以编写以下内容:
let function_1 (x:double) (y:double byref) = 
y <- 6.0

Program.call_func(s, new fn(fun x -> fun y -> function_1 x &y))

这编译,并按预期工作。

注意修改参数 y ,您必须使用 <-运算符(operator)。使用 let y = 6.0声明完全不同的变量来隐藏参数。

关于f# - 将 c# 委托(delegate)与 f# 函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077804/

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