在f#函数中使用c#委托 [英] Using c# delegates with f# functions

查看:100
本文介绍了在f#函数中使用c#委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call a c# function from f# where the c# function takes a function (delegate?) as a parameter and I need this argument to be a f# function. Eg:

示例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->双重byref->单位应该是委托的类型 void fn(double,ref double)

But I get the error that the f# function_1 has type double -> double byref -> unit when it should be the type of the delegate void fn(double, ref double).

我可以强制转换类型吗?还是有错误?

Can I cast the type or something like that? Or is there an error?

推荐答案

如果要通过F#中的函数创建委托,则可以使用 new 运算符,并为其提供函数作为参数:

If you want to create a delegate from a function in F#, you can use the new operator and give it the function as an argument:

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

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

但是,出于某些原因,如果尝试对包含 ref 的委托使用相同的方法,则会出现此错误:

But, for some reason, if try to use the same approach with a delegate that contains ref, you get this error:


此函数值用于构造委托类型,其签名包括byref参数。您必须使用带有2个参数的显式lambda表达式。

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.

因此,如果您遵循错误消息给出的建议,则可以编写以下内容:

So, if you follow the advice given by the error message, you can write the following:

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

这将编译并按预期工作。

This compiles, and works as expected.

请注意,修改参数 y ,则必须使用<-运算符。使用 let y = 6.0 声明完全不同的变量,该变量遮盖了该参数。

Note that to modify the parameter y, you have to use the <- operator. Using let y = 6.0 declares completely different variable that shadows the parameter.

这篇关于在f#函数中使用c#委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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