将 c# 委托与 f# 函数结合使用 [英] Using c# delegates with f# functions

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

问题描述

我试图从 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# 中我尝试过:

In f# I tried:

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 ->unit 当它应该是委托的类型时 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<的委托使用相同的方法/code>,你得到这个错误:

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.

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

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