gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:52:44 25 4
gpt4 key购买 nike

遵循 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 对其进行建模而不是 classes .

你可以这样做:

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

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

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

编译器具有类型推断,这意味着它可以根据您在其中的字段猜测 req 是一个 CustomerRequest,对于 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))

关于c# - 如何在 F# 中实例化类及其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54271752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com