首页 > 解决方案 > 将 FSharpFun 从 C# 传递到 F#

问题描述

F#模块中函数的定义。

module ClassLibrary1.Functions

let checkThis item f =
    if f item then
        printfn "HIT"
    else
        printfn "MISS"

f# 单元测试 - 有效

[<TestMethod>]
    member this.TestFunctions() =
        checkThis 5 (fun x -> x > 3)

在 c# 单元测试中

using ClassLibrary1;

namespace TestProject
{
    [TestClass]
    public class UnitTest1
    {

        [TestMethod]
        public void TestFunctions()
        {
            FSharpFunc<int, bool> s = x => x > 3 // error, how to declare?
            Functions.checkThis(5, s);
        }
     }
}

错误

无法将初始化程序类型“lambda 表达式”转换为目标类型


编辑

截图帮助解答。

在此处输入图像描述

截图 3

在此处输入图像描述

标签: c#c#-to-f#

解决方案


对于最新的 F# 版本 (10.2.3),请使用

var s = FuncConvert.FromFunc(new Func<int, bool>(x => x > 3));

定义了FX_NO_CONVERTER

FSharpFunc<int, bool> s = new Converter<int, bool>(x => x > 3); 
var s = FSharpFunc<int, bool>.FromConverter(x => x > 3);
var s = FuncConvert.ToFSharpFunc(new Converter<int, bool>(x => x > 3));

推荐阅读