F#非平凡的非主要构造函数 [英] F# non-trivial non-primary constructor

查看:89
本文介绍了F#非平凡的非主要构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在调用主要构造函数之前在非主要构造函数中做一些工作,例如像这样的东西:

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)

如果可能的话,我如何实现这一目标(现在我已经考虑过了,我什至不知道是否可以在C#中完成此目标,但是目标类似于您可以在任意位置调用基本构造函数的方式扩展类的构造函数...但是我不想做任何草图,只是在推迟使用主要构造函数之前先处理一下我的论点-也许今天我在计算机屏幕上看得太多了??

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)?

推荐答案

我不知道您做了什么,但这对我有用:

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)

此外,如果要在派生类型中调用基本构造函数并在插入代码之前或之后插入,则语法FYI(注意括号的位置):

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"

这篇关于F#非平凡的非主要构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆