gpt4 book ai didi

f# - 将 system.Object 转换为 F# 中的特定类型

转载 作者:行者123 更新时间:2023-12-02 16:03:48 27 4
gpt4 key购买 nike

我有一个标准类型,用于在具有可选 MessageObject 的函数之间传递消息和对象,即 System.Object。

type StatusMessage = {
Message: string
MessageObject: Object option
Success: bool
}

在下面的特定函数中——我知道消息对象将始终包含以下特定类型,我希望能够在函数中访问它

type SingleCorrectRecord = {
CardTransactionWithOrder: CardWithOrder
Line: RowTransaction
ExchangeVariance: decimal
}

我的职能是:

let getEstimatedVariance(matchedTransactions: StatusMessage list): decimal = 
let exchangeVariance:decimal =
matchedTransactions |> Seq.sumBy(fun mt -> mt.MessageObject.ExchangeVariance)
estimatedVariance

显然 mt.MessageObject 不包含属性“ExchangeVariance”,但我需要能够转换(或拆箱?)该对象,以便它知道它是 SingleCorrectRecord 类型并且我可以访问这些属性。

感谢任何帮助。

最佳答案

您可以在同一个匹配表达式中嵌套带有 union case 模式的动态类型测试:

let exchangeVariance = 
matchedTransactions |> Seq.sumBy (fun mt ->
match mt.MessageObject with
| Some(:? SingleCorrectRecord as scr) -> scr.ExchangeVariance
| _ -> 0M )
// val exchangeVariance : decimal

关于f# - 将 system.Object 转换为 F# 中的特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69949606/

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