简体   繁体   中英

Call F# function that has a function parameter from C#

In F# i have the function:

module ModuleName
let X (y: int -> unit) = ()

How can i call this in C#? Ideally it would look like

ModuleName.X(x => x*x);

But this lambda syntax does not convert implicitly to a FSharpFunc.

The easiest approach would be to expose your API using standard .NET delegate types. In this case, that means that your F# definition should look more like:

let X (y:Action<int>) = ()

However, if you want to keep your F# API the same as it currently is, then you could use FuncConvert.ToFSharpFunc from the C# side:

ModuleName.X(FuncConvert.ToFSharpFunc(x => x*x));

You should be able to do this using the static FSharpFunc.FromConverter method: http://msdn.microsoft.com/en-us/library/ee353520.aspx

ModuleName.X(FSharpFunc.FromConverter(x => x*x));

EDIT: I just noticed that your function calls for an int -> unit but your call specifies an int -> int . To create an FSharpFunc that returns unit, you can use one of the static methods of the FuncConvert static class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM