Parameters and value types F #

The following f # function works fine if I pass references to objects, but will not accept structures or primitives:

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

If I try to call this from C # with:

bool result = false;
TryGetFromSession(TheOneCache.EntryType.SQL,key,out result)

I get The Type bool must be a reference type in order to use it as a parameterIs there a way to handle the F # function descriptor and?

+4
source share
2 answers

The problem is that the value nullin outValue <- nullrestricts the type to a 'Treference type. If it has nullas a valid value, it cannot be a value type!

, Unchecked.defaultOf<'T>. , default(T) #, 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
+8

, "" / F # , , :

let myCast<'T> o = 
 match box o with
 | :? 'T as r -> Some(r)
 | _ -> None


let GetFromSession<'T> entryType key = 
 match HttpContext.Current.Session.[entryType.ToString + key] with 
 | null -> None
 | r -> myCast<'T> r

"" (?) , F #. # , None null, - , , Some; -)

, , , . ...

: https://msdn.microsoft.com/en-us/library/dd233220.aspx http://fsharpforfunandprofit.com/posts/match-expression/

:

, , HttpContext Session , ...

# - None/Some

var x = GetFromSession<MyTypeInSession>(entryType, key)?.Value??defaultValue;

, , ifs buts , .

...

0

Source: https://habr.com/ru/post/1627071/


All Articles