如何在 F# 中实例化 类 及其属性

How to instantiate classes and their properties in F#

遵循代码 C#:

var body = new CustomerRequest
{
    Method = "CREDIT_CARD",
    CreditCard = new Creditcard
    {
        ExpirationMonth = "06",
        ExpirationYear = "2022",
        Number = "4012001037141112",
        Cvc = "123"
    }
};

我是 F# 的新手,我不能像 C# 那样实例化 类,请参阅下面的 F# 代码:

let body = CustomerRequest
(
    Method = "CREDIT_CARD"     // Help here
)

我无法将 C# 转换为 F#

如果您使用的是惯用的 F#,您可以使用 Records instead of classes 来建模。

你可以这样做:

type CreditCard = {
    ExpirationMonth: int;
    //More
}

type CustomerRequest = {
    Method: string;
    CreditCard: CreditCard;
}

let req = {
    Method = "Credit"
    CreditCard = {
        ExpirationMonth = 6
        //More
    }
}

编译器有类型推断,这意味着它可以根据你在其中的字段猜测 req 是一个 CustomerRequestCreditCard 也是如此 - 你可以如果确实需要,请提示类型。

如果您真的想要 类 - 也许您必须与 C# 代码互操作,那么您可以这样做:

type CreditCard2(expirationMonth:int) = 
    member this.ExpirationMonth = expirationMonth

type CustomerRequest2(method: string, creditCard: CreditCard2) = 
    member this.Method = method
    member this.CreditCard = creditCard

let req2 = CustomerRequest2 ("Credit", CreditCard2 (5))

我想这就是您要找的:

CreditCard.fs

namespace Whosebug

type CreditCard() =
    member val ExpirationDate = "" with get, set
    member val ExpirationYear = "" with get, set
    member val Number = "" with get, set
    member val Cvc = "" with get, set

type CustomerRequest() =
    member val Method = "" with get, set
    member val CreditCard = new CreditCard() with get, set

Program.fs

open System
open Whosebug

[<EntryPoint>]
let main argv =
    let body = new CustomerRequest(Method = "CREDIT_CARD",
                                        CreditCard = CreditCard(
                                            ExpirationDate = "06",
                                            ExpirationYear = "2022",
                                            Number = "4012001037141112",
                                            Cvc = "123"
                                        ))
    0

我对 F# 了解不多,所以也许像 David Shaw 使用的那样使用 Records 是更明智的设计。但基本上这会让你在没有参数构造函数和类型中没有可变的非 属性 值的情况下做到这一点。

如果您只想使用 named arguments 来设置您正在构建的 类 的属性:语法与 C# 非常相似。至于缩进的层级,需要和第一个参数对齐。

let body =
    CustomerRequest(
        Method = "CREDIT_CARD",
        CreditCard =
            Creditcard(
                ExpirationMonth = "06",
                ExpirationYear = "2022",
                Number = "4012001037141112",
                Cvc = "123" ) )