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

时间:2019-01-19 21:58:00

标签: c# f# c#-to-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#

3 个答案:

答案 0 :(得分:3)

如果您要进行惯用的F#,则可以使用Records而不是classes对此模型进行建模。

您可以这样做:

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

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

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

编译器具有类型推断功能,这意味着它可以根据您所拥有的字段来猜测reqCustomerRequest,而CreditCard也是相同的-您可以提示如果确实需要,请输入

如果您确实在上课-也许您必须与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))

答案 1 :(得分:2)

我认为这就是您想要的:

CreditCard.fs

namespace StackOverflow

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 StackOverflow

[<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会更好。但是从根本上讲,这将使您无需参数构造函数且类型中没有可变的非属性值就可以做到这一点。

答案 2 :(得分:2)

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

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