简体   繁体   English

与C#库进行F#fsharp互操作(CsvHelper)

[英]F# fsharp interop with C# library (CsvHelper)

I have been successfully using a library CsvHelper to do some CSV manipulation in F# (things that I have not been able to accomplish with Fsharp.Data CsvProvider). 我已经成功地使用库CsvHelper在F#中进行了一些CSV操作(我无法使用Fsharp.Data CsvProvider完成这些操作)。

In their documentation, they manipulate headers through: 在他们的文档中,他们通过以下方式操作标头:

csv.Configuration.PrepareHeaderForMatch = header => header.Replace( " ", string.Empty );

I am trying to do something similar (changing all headers to lowercase), but I haven't figure out how to deal with this delegate. 我正在尝试做类似的事情(将所有标头更改为小写),但是我还没有弄清楚如何处理该委托。

I'm trying the following, but it doesn't compile. 我正在尝试以下操作,但无法编译。

csv.Configuration.PrepareHeaderForMatch = (fun header -> header.ToLower())

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thank you. 谢谢。


I have tried @kaefer advice of assigning the "PrepareHeaderForMatch", since it is a C# getter;setter; 我尝试过@kaefer建议分配“ PrepareHeaderForMatch”的建议,因为它是C#getter; setter;。

csv.Configuration.PrepareHeaderForMatch <- fun header -> header.ToLower()

As noted in my comment, the compiler complaints that of a type mismatch because the c# property is expecting: 如我的评论中所述,编译器抱怨类型不匹配,因为c#属性期望:

System.Func<System.Type, string, string>

在此处输入图片说明

The error you are seeing is probably about type mismatches, or about a function type not supporting the 'equality' constraint. 您看到的错误可能与类型不匹配有关,或者与不支持“相等”约束的函数类型有关。 This is because the expression 这是因为表达式

csv.Configuration.PrepareHeaderForMatch = (fun header -> header.ToLower())

parses as the invocation of the operator Microsoft.FSharp.Core.Operators.(=) with a property getter on the left hand side and an inline function definition on the right hand side. 解析为运算符Microsoft.FSharp.Core.Operators.(=)的调用,左侧带有属性getter,右侧带有内联函数定义。 Instead, you want an assignment expression expr <- expr here, with a property setter invocation on the left hand side: 相反,您需要一个赋值表达式expr <- expr ,在左侧具有属性设置器调用:

csv.Configuration.PrepareHeaderForMatch <- fun header -> header.ToLower()

In the F# language, the = token is a common source of confusion, because depending on the context it can stand for two different things: 在F#语言中, =标记是造成混淆的常见原因,因为取决于上下文,它可以代表两种不同的含义:

  • The generic equality operator = as above, or 通用相等运算符=如上所述,或
  • A binding in the context of value, function, type or member definitions, for example let x = 42 在值,函数,类型或成员定义的上下文中进行绑定,例如let x = 42

Edit Turns out that the expected type of the property in question is System.Func<System.Type, string, string> , which means that you need to supply an extra argument which you subsequently do not use. 编辑原来,所讨论的属性的预期类型为System.Func<System.Type, string, string> ,这意味着您需要提供一个额外的参数,该参数随后将不再使用。 It can be represented by wildcard: fun _ header -> header.ToLower() 可以用通配符表示: fun _ header -> header.ToLower()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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