F# 输出参数和值类型

标签 f# c#-to-f#

如果我传递对对象的引用,以下 f# 函数效果很好,但不会接受结构或基元:

let TryGetFromSession (entryType:EntryType, key, [<Out>]  outValue: 'T byref) =
    match HttpContext.Current.Session.[entryType.ToString + key] with 
             | null -> outValue <- null; false
             | result -> outValue <- result :?> 'T; true

如果我尝试从 C# 调用它:
bool result = false;
TryGetFromSession(TheOneCache.EntryType.SQL,key,out result)

我收到 The Type bool must be a reference type in order to use it as a parameter有没有办法让 F# 函数同时处理两者?

最佳答案

问题在于null值在 outValue <- null限制类型 'T成为引用类型。如果有 null作为有效值,它不能是值类型!

您可以使用 Unchecked.defaultOf<'T> 解决此问题反而。这与 default(T) 相同在 C# 中,它返回 null (对于引用类型)或值类型的空/零值。

let TryGetFromSession (entryType:EntryType, key, [<Out>]  outValue: 'T byref) =
    match HttpContext.Current.Session.[entryType.ToString() + key] with 
    | null -> outValue <- Unchecked.defaultof<'T>; false
    | result -> outValue <- result :?> 'T; true

关于F# 输出参数和值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166020/

相关文章:

c# - 来自 C# 的 F# 区分联合用法

file - F# 将列表输出到文件

f# - 我该如何使用下载的 FsLab 模板?

asynchronous - F# Async.FromBeginEnd 不捕获异常

c#-4.0 - 在 F# 中访问动态属性

parallel-processing - F#如何并行做List.map

f# - 是否可以在 F# 中定义通用扩展方法?

c# - 将 C# 代码转换为 F#(if 语句)

列表的 F# 类型注释