如果我传递对对象的引用,以下 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/