Using c# delegates with f# functions

前端 未结 1 1425
长情又很酷
长情又很酷 2020-12-11 05:43

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:

Sample

相关标签:
1条回答
  • 2020-12-11 06:39

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

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题