gpt4 book ai didi

f# - F# 相当于 C#'s ' out'

转载 作者:行者123 更新时间:2023-12-04 01:30:16 25 4
gpt4 key购买 nike

我正在将 C# 库重写为 F#,我需要翻译以下代码

bool success;
instance.GetValue(0x10, out success);
out 的等价物是什么? F# 中的关键字?

最佳答案

wasatz 的回答和 Max Malook 的回答都不完整。 out 调用方法的三种方式参数。第二种和第三种方式也适用于 ref参数。

对于示例,假设以下类型:

open System.Runtime.InteropServices //for OutAttribute
type SomeType() =
member this.GetValue (key, [<Out>] success : bool byref) =
if key = 10 then
success <- true
"Ten"
else
success <- false
null

还假设我们有一个该类型的实例:
let o = SomeType()

选项1

您可以让 F# 编译器通过将其与返回值进行元组处理来处理 out 参数:
let result1, success1 = o.GetValue 10
let result2, success2 = o.GetValue 11

在 F# 交互式中运行上述行
val success1 : bool = true
val result1 : string = "Ten"
val success2 : bool = false
val result2 : string = null

选项 2

您可以使用可变值,将其地址与 & 一起传递。运算符(operator):
let mutable success3 = false
let result3 = o.GetValue (10, &success3)
let mutable success4 = false
let result4 = o.GetValue (11, &success4)

在 F# 交互中,结果是
val mutable success3 : bool = true
val result3 : string = "Ten"
val mutable success4 : bool = false
val result4 : string = null

当您委托(delegate)给另一个方法时,此选项是最好的,因为您可以将调用方法的 out 参数直接传递给被调用方法。例如,如果您正在实现 IDictionary<_,_> 周围的包装器。 ,您可以编码 TryGetValue方法为
//...
interface IDictionary<'TKey, 'TValue> with
member this.TryGetValue (key, value) = inner.TryGetValue (key, &value)
//...

选项 3

您可以使用引用单元格:
let success5 = ref false
let result5 = o.GetValue (10, success5)
let success6 = ref false
let result6 = o.GetValue (11, success6)

输出:
val success5 : bool ref = {contents = true;}
val result5 : string = "Ten"
val success6 : bool ref = {contents = false;}
val result6 : string = null

警告!

注意不要使用 ref关键字,就像在 C# 中用于输入/输出参数一样。例如,以下内容不会产生预期的结果:
let success7 = false
let result7 = o.GetValue (10, ref success7)

输出:
val success7 : bool = false
val result7 : string = "Ten"

为什么 success7持有值(value) false ?因为 success7是一个不可变的变量。

在 C# 中, ref提请注意您正在传递对变量的引用作为 ref 的参数这一事实。范围。它只是作为保证调用者的程序员知道变量可能被调用的方法修改。然而,在 F# 中, ref创建一个新的引用单元格,其中包含以下表达式的值的副本。

在这种情况下,我们正在创建一个引用单元格,其中包含从 success7 复制的值。变量,但不将该新引用单元分配给任何变量。然后我们将该引用单元格传递给 GetValue 方法,该方法修改引用单元格的内容。因为调用方法没有指向修改单元格的变量,所以它无法读取引用单元格的新值。

关于f# - F# 相当于 C#'s ' out',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691162/

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