如何将F#函数传入C#构造函数?实例化ViewModel遇类型转换错误
解决C#实例化F# ViewModel时的FSharpFunc转换错误
看起来你遇到的核心问题是类型不匹配加上错误的转换方法使用,咱们一步步来解决:
1. 先修正类型参数不匹配的问题
首先看你的F#代码,SubmitFn定义的返回类型是Result<Profile, ValidatedForm>,但在C#里你试图转换成FSharpFunc<ValidatedForm, FSharpResult<ProfileRequest, ValidatedForm>>——这里Profile和ProfileRequest是两个不同的类型,编译器自然会报错。
如果你的ViewModel期望的提交函数返回ProfileRequest,先修改F#的SubmitFn定义和submit函数:
module Try // 把返回类型的Profile改成ProfileRequest,和C#端保持一致 type SubmitFn = ValidatedForm -> Result<ProfileRequest, ValidatedForm> let submit : SubmitFn = fun registration -> Error registration
2. 正确传递F#函数到C#
F#的函数类型'T -> 'U在C#中会被自动编译为Microsoft.FSharp.Core.FSharpFunc<T, U>,所以你不需要手动调用ToConverter(这个方法是用来把FSharpFunc转成C#的Converter<T,U>,方向搞反了)。
只需要确保C#代码引用了Microsoft.FSharp.Core命名空间,然后直接传入Try.submit即可:
using Microsoft.FSharp.Core; // ... // 直接传递F#函数,类型匹配的话编译器会自动识别 DataContext = new ViewModel(Try.submit);
如果还是遇到类型推断问题,可以显式指定类型:
FSharpFunc<ValidatedForm, FSharpResult<ProfileRequest, ValidatedForm>> cs_submit = Try.submit; DataContext = new ViewModel(cs_submit);
为什么原来的代码报错?
ToConverter的作用是将FSharpFunc<T,U>转换为C#标准的Converter<T,U>委托,而不是把F#方法组转成FSharpFunc。- 类型参数不匹配:F#返回
Profile,C#期望ProfileRequest,这是编译器报错的直接原因。
内容的提问来源于stack exchange,提问作者Scott Nimrod
相关产品推荐
相关产品推荐

