简体   繁体   中英

F# class assign an object value to another object

Coming from a C# background, I'm trying to assign an instance of a class to another instance of a class in F# but I'm getting the error 'Type Initialisation Exception'

My Code is

//filename is CCPType.fs

module CCPType =

    type CCPClass() = class
        let mutable p = Unchecked.defaultof<int>
        let mutable d = Unchecked.defaultof<int[,]>

        member self.P
            with get () = p
            and set (value) = p <- value

        member self.D
            with get () = d
            and set (value) = d <- value

    end

//filename is Programme.fs

Module Start =

    [<EntryPoint>]
    let main argv = 
        let record = FileParser.ParseTextToCCPRecord(text) // returns CCPClass
        let z = Optimiser.Execute(record) //arg is of type CCPClass

//filename is Optimiser.fs

module Optimiser =

    let mutable ccpDataSet = CCPClass()

The following snippets are all part of Optimiser.fs within the module Optimiser. I've tried the following

    let Execute record =
        ccpDataSet <- record

and I've also tried

    let Execute(record: CCPClass) =
        ccpDataSet = new CCPClass()
        ccpDataSet.P <- record.P
        ccpDataSet.D <- record.D

and I've also tried

    let Execute(record: CCPClass) =
        ccpDataSet <- new CCPClass()
        ccpDataSet.P <- record.P
        ccpDataSet.D <- record.D

and I've also tried

    let Execute record =
        ccpDataSet.P <- record.P
        ccpDataSet.D <- record.D

and I've tried quite a few different ways but I still can't copy one instantiated class to another.

I get the error, 'An unhandled exception of type "System.TypeInitializationException"'.

'"ccpDataSet" threw an exception of type "System.TypeInitializationException"'.

Any ideas? Thanks

Thanks to Fyodor and Carsten, I figured it out.

let mutable private OpenD : bool[] = Array.zeroCreate<bool> ccpDataSet.D.Length

Since I'm new to F# it doesn't behave like C#, I was trying to set the length of OpenD to a null instance. Changed it to 0 and it works :)

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