F# non-trivial non-primary constructor

北城以北 提交于 2019-12-21 22:24:52

问题


I want to do some work in a non-primary constructor before calling the primary constructor, e.g. something like this:

type Foo(a:int,b:int) =
    let a = a
    let b = b
    new(s:string) =
        //...work here (intermediate let bindings)
        let _a = ...
        let _b = ...
        Foo(_a,_b)

If possible, how can I achieve this (now that I think about it, I'm not even sure if this can be done in C#, but the goal is similar to how you can call base constructors anywhere you like in an extending class constructor... but I don't want to do anything so sketch, just process my arguments a bit before deferring to the primary constructor -- or maybe I've been looking at computer screens too much today)?


回答1:


I don't know what you did but this works for me:

type Foo(a:int,b:int) =
    let a = a
    let b = b
    new (s:string) =
        printfn "some side effect"
        let _a = s.Length
        let _b = 1
        Foo(_a,_b)

In addition if you want to call base constructors in a derived type and pre or post insert code, here's the syntax FYI (beware of the braces placement):

type DFoo =
    inherit Foo

    new (a,b) =
        printfn "perform some validation here"
        let c = 0 // or bind stuff
        {
            inherit Foo(a,b)
        }
    new (s:string) =
        {
            inherit Foo(s)
        }
        then if s.Length = 0 then printfn "post ctor side effect"


来源:https://stackoverflow.com/questions/4466981/f-non-trivial-non-primary-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!