F#输出参数和值类型

jac*_*ott 4 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
Run Code Online (Sandbox Code Playgroud)

如果我尝试用C#调用它:

bool result = false;
TryGetFromSession(TheOneCache.EntryType.SQL,key,out result)
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*cek 8

问题是该nulloutValue <- 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
Run Code Online (Sandbox Code Playgroud)