F # class constructor without args arguments --- error using filehelpers wtih f #

I followed the link to parse CSV using F # and filehelpers . got a compiler error for the following code"The record class oneRow need a constructor with no args (public or private)"

[<DelimitedRecord(",")>]
type oneRow=
  class
    [<FieldConverter(ConverterKind.Date, "M/d/yyyy")>]
    val date: DateTime
    val value: bool
  end
let engine = new FileHelperEngine(typeof<oneRow>)
let tmp = engine.ReadFile("test.csv")

EDIT The solution looks rather verbose than the C # version. I need to add (), mutableand[<DefaultValue>]

  type oneRow() =
      class
        [<FieldConverter(ConverterKind.Date, "M/d/yyyy")>]
        [<DefaultValue>]
        val mutable date: DateTime
        [<DefaultValue>]
        val mutable value: bool
      end

But similar code works in C # without specifying a constructor. Can someone help me fix the F # code? Thank you

+3
source share
5 answers

C # will create you a constructor. F # is not (presumably because parameterless constructors imply mutability, and therefore not recommended.)

, - , - .

+2

- . (2 ), . , - :

[<DelimitedRecord(",")>]
type OneRow
   ( [<FieldConverter(ConverterKind.Date, "M/d/yyyy")>] 
     date:DateTime,
     value:bool ) =
   member x.Date = date
   member x.Value = value

, (, , , , ). , , , ( ).

+2

, type oneRow () =

0

, , , ctor oneRow.

new () = { date = new DateTime() ; value = false}
0

Most messages regarding FileHelpers are rather outdated. In some cases, it is recommended to use a csv-type provider instead. You can use the attribute CLIMutablein the F # record to have a default constructor, in which case FileHelpers will happily write and read the csv file:

#if INTERACTIVE
#I @"..\packages\FileHelpers\lib\net45"
#r "FileHelpers.dll"
#endif

open FileHelpers
open System

[<DelimitedRecord(",");CLIMutable>]
type TestFileHelp =
    {test1:string
     test2:string
     [<FieldConverter(ConverterKind.Date, "yyyy/MM/dd")>]
     date:DateTime
    }

let f1 = [|{test1="a";test2="b";date=DateTime.Now};{test1="c";test2="d";date=DateTime.Now}|]
let fengine = new FileHelperEngine<TestFileHelp>()
fengine.WriteFile(@"c:\tmp\testrec.csv",f1)    
0
source

Source: https://habr.com/ru/post/1791534/


All Articles